简体   繁体   中英

How to check answer from user input in Java with JOptionPane

    tambah = new JButton("Tambah");
    tambah.setBounds(40, 100, 100, 50);
    tambah.setForeground(Color.black);
    tambah.setBackground(Color.white);
    window2.add(tambah);
    tambah.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        Random rand = new Random();
        int upper = 100;
        int lower = 100;
            
        int int_random = rand.nextInt(upper);
        int int_random2 = rand.nextInt(lower);
        JOptionPane.showInputDialog(null, int_random + "+" + int_random2 );
            
        }
    });

i want to make a quizz app with java. first they will click the button then JOptionPane will show the question and when the user submit their answer, how can i check their answer?? sorry for my bad english

The JOptionPane.showInputDialog method is String returns method, so you can use this line of code to get the answer:

String answer = JOptionPane.showInputDialog(null, "Enter your name");

answer is equals to the user input. To get an integer, use this:

int answer = Integer.parseInt(JOptionPane.showInputDialog(null, "7 + 8"));

answer is equals to the user input. If user enter a NaN (not a number) like hello , NumberFormatException will thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM