My expectation:
If the user types an Int which is not in the right range, the program will give him another chance until the user gives the right type.
So, I need a while block. But I got an infinite loop.
My code:
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TestInput {
public static void main (String[] args) {
boolean keepRunning = true;
while (keepRunning) {
try {
System.out.println("Start --- ");
Integer selection = inputSelection();
//Integer selection = Integer.parseInt(selectionString);
String email;
switch (selection) {
case 1:
// inputDate();
System.out.println("Do 1");
break;
case 2:
//inputEmail();
System.out.println("Do 2");
break;
case 3:
//inputName();
System.out.println("Do 3");
break;
case 5:
// Exit
keepRunning = false;
break;
default:
System.out.println("Please enter a number between 1 and 3: ");
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static Integer inputSelection () {
Integer selection = 0;
try (Scanner scanner = new Scanner(System.in)) {
if (scanner.hasNext()) {
selection = scanner.nextInt(); // reads only one int. does not finish the line.
scanner.nextLine(); // consume '\n' to finish the line
}
} catch (NoSuchElementException ex) {
throw ex;
}
return selection;
}
}
DOCs I read:
Resetting a .nextLine() Scanner
Using Scanner.nextLine() after Scanner.nextInt()
Scanner is skipping nextLine() after using next() or nextFoo()?
How to use java.util.Scanner to correctly read user input from System.in and act on it?
The Scanner Class String formatting in Java Scanner class Java Scanner doesn't wait for user input
String formatting in Java Scanner class
Those answers do not work for me. I still get an infinite loop. Any advice? Thank you.
scanner.next()? - cs1349459