簡單的Java圖形化抽獎程式
阿新 • • 發佈:2021-11-28
要求:設計圖形介面程式實現抽獎遊戲。玩家輸入0-9範圍之內的一個數字,抽獎開始後,隨機產生0-9範圍內的3個數字,如果3個數字都和玩家輸入的數字相同,則獲得一等獎,有兩個數字和玩家輸入的數字相同,則獲得二等獎,有一個數字和玩家輸入的數字相同,則獲得三等獎。如果沒有任何一個數組和玩家輸入的數字相同,則表示沒有獲獎
import java.awt.*; import java.awt.event.*; import java.util.Random; public class chu { public static void main(String[] args) { JFrame title = new JFrame("抽獎"); JLabel label = new JLabel(); JButton button = new JButton("開始抽獎"); final JTextField textField = new JTextField(); title.setSize(500, 360); title.setLocation(200, 200); title.setLayout(new FlowLayout()); textField.setPreferredSize(new Dimension(150, 40)); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String[] num = new String[3]; for(int i=0;i<3;i++) num[i] = String.valueOf(new Random().nextInt(10) + 1); int m=0; String text = textField.getText(); for(int j=0;j<3;j++) if(text.equals(num[j])) m++; if(text.equals("")||text==null) { JOptionPane.showMessageDialog(null, "輸入錯誤"); } else{ if (m == 0) {JOptionPane.showMessageDialog(null, "獲獎的號碼為"+num[0]+num[1]+num[2]+"\n"+"所以您沒有中獎");} if (m == 1) {JOptionPane.showMessageDialog(null, "獲獎的號碼為"+num[0]+num[1]+num[2]+"\n"+"所以您獲得了三等獎");} if (m == 2) {JOptionPane.showMessageDialog(null, "獲獎的號碼為"+num[0]+num[1]+num[2]+"\n"+"所以您獲得了二等獎");} if (m == 3) {JOptionPane.showMessageDialog(null, "獲獎的號碼為"+num[0]+num[1]+num[2]+"\n"+"所以您獲得了一等獎");} } } }); title.add(label); title.add(textField); title.add(button); title.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); title.setVisible(true); } }