Java - scanner - skips my last nextLine () request

So, I create an instance Scanner scanmuch earlier, but it skips my second scan.nextLine()after scan.nextInt(). I do not understand why he misses it?

     System.out.println("Something: ");

        String name = scan.nextLine();

        System.out.println("Something?: ");

        int number = scan.nextInt();

        System.out.println("Something?: ");

        String insurer = scan.nextLine();

        System.out.println("Something?: ");

        String another = scan.nextLine();
+2
source share
4 answers

because when you enter a number

    int number = scan.nextInt();

you enter some number and press enter, it takes only the number and saves a new line character in the buffer

therefore, it nextLine()will just see the terminator symbol, and it will assume that it is empty as input, to fix it, add one scan.nextLine()after the processint

eg:

 System.out.println("Something?: ");

 int number = scan.nextInt();

 scan.nextLine(); // <-- 
+7
source

int number = scan.nextInt();, , , scan.nextLine();

,

    ....
    System.out.println("Something?: ");
    int number = scan.nextInt();
    scan.nextLine();                      // add this
    System.out.println("Something?: ");
    String insurer = scan.nextLine();
+4

* nextInt() \n. , ,   , nextInt() .

* , nextLine() nextInt, nextLine()
  , .

enter image description here

int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();

System.out.println("Something?: ");
String insurer = scan.nextLine();

// .

String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();

int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();
+4

- .

:

: nextInt(), nextLine()

: nextInt() , ENTER . nextInt() , \n ENTER . nextLine() , , , \n. , , \n - nextInt() [ jdk8u77].

, nextLine .

: scannerObj.nextLine() scannerObj.nextInt()

+1

All Articles