按钮事件,判断从文本框中输入的数是否为素数

来源:互联网 发布:thinkphp网站源码 编辑:程序博客网 时间:2024/05/29 09:03

 

 

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package homework;


import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author Administrator
 */
public class PrimeJudge extends JFrame implements ActionListener {

    private JTextField inputPrime;
    private JButton judgePrime;

    /** Creates a new instance of PrimeJudge */
    public PrimeJudge() {
        this.setTitle("素数判断");
        this.setSize(400, 400);
        this.setIconImage(new ImageIcon("qsp.gif").getImage());

        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent evt) {
                if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(PrimeJudge.this, "Are you sure?", "Exit?", JOptionPane.YES_NO_OPTION)) {
                    System.exit(0);
                }
            }
        });

        this.buildContent();

        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    private void buildContent() {
        inputPrime = new JTextField(10);
        judgePrime = new JButton("判断是否为素数");
        judgePrime.addActionListener(this);

        JPanel panel = new JPanel();
        panel.add(new JLabel("请输入一个数(n>=2)"));
        panel.add(inputPrime);
        panel.add(judgePrime);

        this.getContentPane().add(panel, "North");
    }

    public static boolean isPrime(int n) {
        for (int i = 2; i <= (int) Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }

        return true;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == judgePrime) {
            try {
                int n = Integer.parseInt(inputPrime.getText());
                if (n < 2) {
                    JOptionPane.showMessageDialog(this, "这个数 < 2 !");
                    return;
                }
                boolean is = PrimeJudge.isPrime(n);
                JOptionPane.showMessageDialog(this, n + (is ? " i 是" : " 不是") + " 一个素数.");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
    }

    public static void test() {
        new PrimeJudge();
    }

    public static void main(String[] args) {
        PrimeJudge.test();
    }
}

原创粉丝点击