Java利用數組隨機抽取幸運觀眾


編寫程序,事先將所有觀眾姓名輸入數組,然后獲得數組元素的總數量,最后在數組元素中隨機抽取元素的下標,根據抽取的下標獲得幸運觀眾的姓名。

思路如下:

  1. 定義輸入框的按鍵事件,使用KeyEvent類的getKeyChar()函數判斷其是否是回車字符,若不是則不作處理;
  2. 使用isEmpty()函數判斷文本框中是否有字符串,如果沒有字符串則不做處理;
  3. 若為合法輸入則通過JTextArea類的append()方法把輸入人名與回車符添加到人員列表;
  4. 使用selectAll()方法選擇文本框所有字符;
  5. 定義點擊“抽取”按鈕時執行的函數,通過JTextArea類的getText()方法獲取人員列表文本,存入字符串;
  6. 創建一個字符串型一維數組,將之前的字符串按回車符分割后存入該數組;
  7. 通過Math.random()生成隨機數組索引,作為中獎者的數組下標;
  8. 定義包含格式參數的中獎信息;
  9. 通過String類的format()方法為中獎信息添加人員參數;
  10. 使用JTextArea類的setText()方法在文本域顯示中獎信息;
  11. 定義點擊“退出”按鈕時執行的函數,使用System.exit(0)方法退出程序。

代碼如下:

package cn.edu.xidian.crytoll;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class ArrayExample {

	private JFrame frame;
	private JTextField textField;
	private JScrollPane scrollPane;
	private JLabel label_1;
	JTextArea textArea = new JTextArea();
	private JTextArea textArea_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ArrayExample window = new ArrayExample();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ArrayExample() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("利用數組隨機抽取幸運觀眾");
		frame.setBounds(100, 100, 500, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JLabel label = new JLabel("\u8F93\u5165\u5728\u573A\u89C2\u4F17\u59D3\u540D\u6309\u56DE\u8F66");
		label.setBounds(10, 10, 132, 15);
		frame.getContentPane().add(label);
		
		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				do_textField_keyPressed(e);
			}
		});
		textField.setBounds(10, 35, 132, 21);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 66, 132, 185);
		frame.getContentPane().add(scrollPane);		
		
		textArea_1 = new JTextArea();
		scrollPane.setViewportView(textArea_1);
		
		label_1 = new JLabel("\u9009\u53D6\u89C2\u4F17\u4EBA\u5458\uFF1A");
		label_1.setBounds(180, 10, 132, 15);
		frame.getContentPane().add(label_1);
		
		
		textArea.setBounds(180, 34, 214, 217);
		frame.getContentPane().add(textArea);
		
		JButton button = new JButton("\u62BD\u53D6");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				do_button_actionPerformed(e);
			}
		});
		button.setBounds(404, 187, 70, 23);
		frame.getContentPane().add(button);
		
		JButton button_1 = new JButton("\u9000\u51FA");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				do_button_1_actionPerformed(e);
			}
		});
		button_1.setBounds(404, 228, 70, 23);
		frame.getContentPane().add(button_1);
	}
	protected void do_textField_keyPressed(KeyEvent e) {
        if (e.getKeyChar() != '\n')// 不是回車字符不做處理
            return;
        String name = textField.getText();
        if (name.isEmpty())// 如果文本框沒有字符串不做處理
            return;
        textArea_1.append(name + "\n");// 把輸入人名與回車符添加到人員列表
        textField.selectAll();// 選擇文本框所有字符
    }
	protected void do_button_actionPerformed(ActionEvent e) {
        String perstring = textArea_1.getText();// 獲取人員列表文本
        String[] personnelArray = perstring.split("\n{1,}");// 獲取人員數組
        int index = (int) (Math.random() * personnelArray.length);// 生成隨機數組索引
        // 定義包含格式參數的中獎信息
        String formatArg = "本次抽取觀眾人員:\n\t%1$s\n恭喜%1$5s成為本次觀眾抽獎的大獎得主。"
                + "\n\n我們將為%1$5s頒發:\n\t過期的酸奶二十箱。";
        // 為中獎信息添加人員參數
        String info = String.format(formatArg, personnelArray[index]);
        textArea.setText(info);// 在文本域顯示中獎信息
    }
	protected void do_button_1_actionPerformed(ActionEvent e) {
		System.exit(0);
    }
}

  效果如圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM