JOptionPane和While循环(用户输入添加)

时间:2013-12-15 17:02:40

标签: loops while-loop joptionpane addition

    package iCanDoIt;

    import java.util.Scanner;

    import javax.swing.JOptionPane;

    public class Practice {

        public static void main(String[] args) {

        String msg=JOptionPane.showInputDialog("Enter a number");
        int num1=Integer.parseInt(msg);
        String msg2=JOptionPane.showInputDialog("enter another number");
        int num2=Integer.parseInt(msg2);
        int addition=num1+num2;

        String msg3=JOptionPane.showInputDialog("What is" + num1 + "+ " + num2 + " ? ");

        int answer=Integer.parseInt(msg3);

        while(num1+num2!=answer){

            JOptionPane.showMessageDialog(null,"try again");
            String answer2=JOptionPane.showInputDialog("wrong. what is " + num1 + "+" + num2 + "?");
            int answer3=Integer.parseInt(answer2);

        if (num1+num2==answer3)

            JOptionPane.showMessageDialog(null,"GREAT job");


        }
        System.exit(0);

        }


    }

我是JAVA的初学者。

扫描仪输入似乎很容易理解,但由于某种原因,我在使用JOptionPane时遇到了困难。

无论如何,我的问题是......即使我得到了正确答案,我仍然会“再试一次”

你可以告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您永远不会更新answer

更改此

int answer3=Integer.parseInt(answer2);
if (num1+num2==answer3)

到这个

answer=Integer.parseInt(answer2);
if (num1+num2==answer)

您还可以通过在循环外移动最终消息对话框来摆脱if (num1+num2==answer)检查:

    int answer=Integer.parseInt(msg3);

    while(num1+num2!=answer){

        JOptionPane.showMessageDialog(null,"try again");
        String answer2=JOptionPane.showInputDialog("wrong. what is " + num1 + "+" + num2 + "?");
        answer=Integer.parseInt(answer2);

    }
    JOptionPane.showMessageDialog(null,"GREAT job");
    System.exit(0);