0

I often struggle with Java scanner. In this case, if I don't create a new scanner object inside the if statement, it does not allow me to enter the string. The complier shows no error but I don't understand why it behaves like that. I want to know the best practice to deal with this situation.

import java.util.Scanner;

public class testing {

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter an integer:");
        int x = scanner.nextInt();
        System.out.println(x);
        if (x == 1) {
            System.out.println("Enter a string");
            //If I use "scanner" instead of "scanner2" here,
            //or if I do not create a new scanner object,
            //the program would not allow me to enter a string, 
            //and it instantly jumps to "The end".
            Scanner scanner2 = new Scanner(System.in);
            String y = scanner2.nextLine();
            System.out.println(y);
            scanner2.close();
        } else {
            System.out.println("The end.");
        } scanner.close();
    }
}
  • For the record, opening multiple `Scanner` objects is not the correct solution for this problem. The correct solution is to understand precisely what `nextInt()` is doing with the input stream and take it into account. – Stephen C Feb 05 '22 at 12:16
  • This is a problem when using Scanner `nextXXX()` methods (other than `nextLine()`). They don't consume the newline character from the input stream when the ENTER key is hit so what happens is that it gets carried over to the first 'nextLine()` method encountered and since it's a newline character the `nextLine()` method accepts it as input and gives the impression that the input request was passed over. Directly after your last `nextInt()` call add this line of code: `scanner.nextLine();`. Now you can get rid of that extra Scanner object and just use `scanner`. – DevilsHnd - 退職した Feb 05 '22 at 13:36

0 Answers0