1

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?

Gaurav Manral
  • 600
  • 3
  • 7
  • 22
helm
  • 673
  • 2
  • 14
  • 25
  • You can create a parser to check if your input is a string or an integer based on if it contains only numbers or also letters – JREN Jul 02 '13 at 09:27
  • for a start, in `choose()` it should be `boolean` not `Boolean` – imulsion Jul 02 '13 at 09:27

2 Answers2

3

nextInt() is not going to consume the EOL. So, either scan for Int as

 int choice = Integer.parseInt(scanner.nextLine());

or, consume the extra new line

 int choice = scanner.nextInt();
 scanner.nextLine(); // Skip
Ravi K Thapliyal
  • 46,997
  • 8
  • 70
  • 84
1

scanner.nextInt() does not consume the line-end. You could wrap the nextLine in a while loop and ask for input again if the line is empty.

Peter Crotty
  • 311
  • 2
  • 9