Search code examples
loopswhile-loopjoptionpaneaddition

JOptionPane and While Loop (user input 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);

        }


    }

I am a beginner at JAVA.

Scanner input seems pretty easy to understand but for some reason I am having a difficult time using JOptionPane.

Anyway, my problem is...Even after I get the answer correct, I keep getting "try again"

Could you please tell me what I am doing wrong?


Solution

  • You're never updating answer.

    Change this

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

    to this

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

    You could also get rid of the if (num1+num2==answer) check by moving your final message dialog outside the loop:

        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);