I am having this problem a lot. When I use a Scanner a lot of times, it doesn't get input from user.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.nextLine();
System.out.println("4---");
String try4 = scan.nextLine();
When I run this code, result it :
1---
12
2---
321
3---
4---
aa
As you can see, it skipped at 3rd input. Why this is happening? I solve this problem by using new Scanners, sometimes I have 5-6 different Scanners and it looks so complicated. Another problem is : there is an error "Resource leak: scan is never closed". I am really confused.
The problem is that by using scanner.nextInt()
you only read an integer value, but not the whole line and you don't consume the newline character (\n
) that is appended to the line when you press Enter.
Then, when you process reading with scanner.nextLine()
you consume the newline character (\n
) and from the previous row and don't read the line you want to read. In order to force it to read it, you have to add an additional input.nextLine()
statement.
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
scan.nextLine(); //<-- fake statement, to move the cursor on the next line
String try3 = scan.nextLine();
Not related to the question, you have to close the Scanner
, after finishing work, otherwise the compiler complains with a warning:
scan.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With