This question has already been answered:

There is the following code:

String tmp="string"; Scanner sc = new Scanner(System.in); while (true) { //some code switch (sc.nextInt()) { case 1: ... case 2: ... case 3: ... case 4: System.out.print("Введите критерий: "); tmp = sc.nextLine(); System.out.println("tmp= " + tmp); break; } 

So, after entering 4 and, accordingly, moving to case 4: I am not offered to enter a string, but simply write an empty string in tmp and the program moves to the next iteration. I read about Scanner on different sites, but did not understand the peculiarity of his work, because of which I had this incident. Explain, please.

Reported as a duplicate by members of Pavel Parshin , aleksandr barakin , VAndrJ , cheops , Community Spirit 25 May '16 at 9:28 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    Add another sc.nextLine(); before tmp = sc.nextLine(); so that was System.out.print("Введите критерий: "); sc.nextLine(); tmp = sc.nextLine(); System.out.println("tmp= " + tmp); break; System.out.print("Введите критерий: "); sc.nextLine(); tmp = sc.nextLine(); System.out.println("tmp= " + tmp); break; - Alexey Shimansky

1 answer 1

Your problem was asked and resolved with enSO .

When you type a number on the keyboard and press Enter , then Enter adds \n to the end. The problem is that the Scanner#nextInt does not return the rest of the string \n , but only reads the number. When you specify Scanner#nextLine , it reads this very remainder of the line - \n , and the next nextLine() already considers exactly the next line you want to receive.


The solution is to add another nextLine() after nextInt() :

  switch (sc.nextInt()) { case 1: ... case 2: ... case 3: ... case 4: sc.nextLine(); System.out.println("Введите критерий: "); tmp = sc.nextLine(); System.out.println("tmp = " + tmp); break; }