You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Java测验APP中用JOptionPane验证用户答题结果?

How to Validate User Answers in Your Java Quiz App

Hey there! Let's get that answer validation working for your addition quiz. Right now, your code generates the problem and asks for input—but it doesn't check if the user got it right. Here's how to update your ActionListener to handle that:

Modified Code Snippet

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; // Quick note: lower is set to 100 here, so rand.nextInt(lower) generates 0-99. If you want numbers starting at 100, use rand.nextInt(upper) + lower instead!
        int num1 = rand.nextInt(upper);
        int num2 = rand.nextInt(lower);
        int correctAnswer = num1 + num2;

        // Show the quiz prompt and capture user input
        String userInput = JOptionPane.showInputDialog(null, num1 + " + " + num2 + " = ?");
        
        // Validate input and check answer
        if (userInput != null) { // Handle case where user clicks "Cancel"
            try {
                int userAnswer = Integer.parseInt(userInput);
                if (userAnswer == correctAnswer) {
                    JOptionPane.showMessageDialog(null, "Perfect! That's the right answer! 🎉");
                } else {
                    JOptionPane.showMessageDialog(null, "Oops, close but not quite. The correct answer is: " + correctAnswer);
                }
            } catch (NumberFormatException ex) {
                // Catch non-numeric input to avoid crashes
                JOptionPane.showMessageDialog(null, "Please enter a valid whole number!");
            }
        }
    }
});

Key Changes Explained

  • Save the correct answer: We calculate correctAnswer right after generating the two random numbers so we have a reference to compare against.
  • Capture user input: We store the result of showInputDialog instead of just calling it—this lets us process what the user entered.
  • Handle cancellation: We check if userInput is null (when the user clicks "Cancel") to skip unnecessary processing.
  • Safe input parsing: The try-catch block around Integer.parseInt prevents your app from crashing if the user enters text instead of a number.
  • User feedback: We pop up clear messages to tell the user if they got it right, wrong, or entered invalid input.

内容的提问来源于stack exchange,提问作者Friko Simon

火山引擎 最新活动