Search code examples
javaintjoptionpanedo-while

How to print a message if the do while loop condition is not met


How would I print a message saying "Error: you have to enter a number between 0 and 5", then allowing the user to input again

 int number;
 do 
  {
     String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
     number = Integer.parseInt(textinput);
  } while (!(number >= 0 && number <= 5));

Solution

  • The simplest method which alters your original code the least is as follows:

    int number;
    do {
        String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
        number = Integer.parseInt(textinput);
        if((number < 0) || (number > 5) {
            //show error message
            continue;  //continue isn't absolutely necessary here, but perhaps for readability
        }
    } while (!(number >= 0 && number <= 5));
    

    Although I find this a little clunky and redundant, you're essentially checking the same condition twice. I'd go with a method more like the following:

    int number;
    String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5");
    while(true) {
        number = Integer.parseInt(textinput);
        if((number >= 0 && number <= 5)) {
            //show error message and prompt for another input
            contine; //As with before, continue isn't necessary here, but could add readability
        } else /*input was good*/ { break; /*exit while loop*/ }
    }