Domanda

String error = "Write a number below, between 1-9;";
int number;
do {
    String userentered = JOptionPane.showInputDialog(error);
    number = Integer.parseInt(userentered);
    if (number < 0 && number > 10) {
        error = "Error";
    }
} while (number > 0 && number < 10);

I want to trap the user in this do while loop, until there have provided the correct answer, e.g. number between 1-9, right now. Right now, when the user types in a letter or leaves the field black and click ok, the optionpane closes but I want it to stay open until the correct input is given. Right now, also if the user types in the correct input it gives them the error message but if there type in a wrong input it closes.

È stato utile?

Soluzione 3

You have to add the parseInt method in try-catch block. Also modify the condition to be number < 1 || number > 9. finally you have to initialize the number with invalid value, lets say -1

String error = "Write a number below, between 1-9;";
int number = -1;
do {
    try {
        String userentered = JOptionPane.showInputDialog(error);
        number = Integer.parseInt(userentered);
        if (number < 1 || number > 9) {
            error = "Error";
        }
    } catch (HeadlessException | NumberFormatException e) {
        error = "Error";
    }
} while (number < 1 || number > 9);

Altri suggerimenti

You need to change the while condition of the do-while loop. Currently it is looping if the number is within the range, but your requirement is the exact reverse of it.

while (!(number > 0 && number < 10)); // Keep looping if the number is outside the range.

Note: The Integer.parseInt() will throw a java.lang.NumberFormatException if the improper inputs are not handled properly.

It's Simple, do while loop is entry control loop. so we need to stat from one less value.

            String errorMsg = "Write a number below, between 1-9;";
    int number = 0;
    do {
        try {
            String usernum = JOptionPane.showInputDialog(errorMsg);
            number = Integer.parseInt(usernum);
            if (number < 1 || number > 9) {
                errorMsg = "Error";
            }
        } catch (Exception e) {
            errorMsg = "Error";
        }
    } while (number < 1 || number > 9);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top