I would like to find a way to ask the user to insert a number between 2 and 10, if the user inserts a different number than an error number and asks it again and if the user inserts a letter that is also error and returns to ask. What I have been able to do and what I have found are several ways, but on the one hand it gives an error in the sense that it detects that it is not among those figures, it gives you an error message and you insert a letter and it does not return to a loop.
public static void main(String[] args) {
//kb = keyboard (teclado)
Scanner kb = new Scanner(System.in);
boolean out = true;
//n = number
int n = 0;
//loop
while (out) {
System.out.println("Inserta un número entre 2 y 10.");
if (kb.hasNextInt()) {
n = kb.nextInt();
if ((n >= 2 && n <= 10)) {
out = false;
} else {
System.out.println("Por favor inserta solo entre 2 y 10");
kb.next();
}
out = false;
} else {
System.out.println("No es un número, vuele a intentarlo!");
kb.next();
}
}
out = true;
}
}
Another solution found on forums would be this ... but make the mistake you make, always telling you the same phrase.
do {
System.out.print("Choose a number between[2-10]");
while(!kb.hasNextInt()){
kb.nextLine();
System.out.println("It's not a valid number.");
}
n = kb.nextInt();
} while ((v<=1 || v>=11));
And finally another more complex solution would be this
final Scanner kb = new Scanner(System.in);
Integer temp = null;
while (temp == null) {
System.out.println("Enter a number between 2 and 10.");
final String input = kb.nextLine();
try {
final Integer value = Integer.valueOf(input);
if (value >= 2 && value < 10) {
temp = value;
} else {
System.out.println("Bad number, try again");
}
} catch (NumberFormatException ex) {
System.out.println("Not a number, try again");
}
}
int n = temp;
To see what possible solution can be found.