For a console menu in Java, I sometimes want to read integers and some strings. I have these two functions:
To get a String:
public String enterString(String question) {
System.out.println(question);
return scanner.nextLine();
}
To get an int (for a switch statement later):
public int choose(int b, String question) {
Boolean chosen = false;
while(!chosen) {
chosen = true;
System.out.println(question);
int choice = scanner.nextInt();
if(choice >= 0 && choice <= b) {
return choice;
}
else {
chosen = false;
System.out.println("Not a valid choice.");
}
}
return 0; //the compiler complains otherwise
}
However, if I use enterString()
first and then choose()
and then enterString()
, it seems to use the newline from choose. Entering scanner.nextLine()
at various places (start and end of each function) always caused problems.
How can I make any combination of the two work?