Search code examples
javaloopsjoptionpane

How to make a simple loop through JOptionPane


I'm new and couldn't find the exact answer I was looking for. I am trying to create a very simple loop using JOptionPane where I insert values between 1-10 and keep looping it. If the value is past 10 or below 1 you should ask the User to try again. So far I have this. If the value hits 0, then the program should end.

    String ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
    int number = Integer.parseInt(ans_s);
    if (number > 10 || number < 0) {
    JOptionPane.showMessageDialog( null, "Please Try Again");
    ans_s = JOptionPane.showInputDialog( "Please enter a number between 1-10 (0 to stop)");
    number = Integer.parseInt(ans_s);
    }
    else if (number < 10 || number > 0) {
    ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
 
    }
    else if (number == 0) {
        
     JOptionPane.showMessageDialog(null, "Finished");
    }

Nothing seems to loop so I just need some guidance.


Solution

  • You need a loop structure,

    boolean control_statement = true;
    while (control_statement) {
        codeInThisMethodWillLoop(); //Until control_statement = false
    }
    

    or

    final int maxLoops = 10; //can be any number
    for (int loopCounter = 0; loopCounter < maxLoops; loopCounter++) {
        codeInThisMethodWillLoop(); //Until loopCounter = maxLoops
    }
    

    in your case

    int number = -1;
    while (number != 0) {
        String ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
        number = Integer.parseInt(ans_s);
        if (number > 10 || number < 0) {
            JOptionPane.showMessageDialog( null, "Please Try Again");
            ans_s = JOptionPane.showInputDialog( "Please enter a number between 1-10 (0 to stop)");
            number = Integer.parseInt(ans_s);
        }
        else if (number < 10 || number > 0) {
            ans_s = JOptionPane.showInputDialog( "Please enter a rating between 1-10 (0 to stop)");
        }
        else if (number == 0) {
             JOptionPane.showMessageDialog(null, "Finished");
        }
    }