Scanner.nextLine () does not act correctly after Scanner.nextInt ()

11

I have this code:

Scanner scan = new Scanner(System.in);

String s2 = scan.nextLine();
int i2    = scan.nextInt();

System.out.println("natural= " + i2);
System.out.println("cadena = " + s2);

scan.close();

That works correctly:

  

This is a chain
  1714
  natural = 1714
  string = This is a string

But if I change the order of the Scanner lines:

int i2    = scan.nextInt();
String s2 = scan.nextLine();

Ignore line scan.nextLine() and give me the result just after entering the int

  

1714
  natural = 1714
  string =

Does anyone know what is happening and how to solve it?

    
asked by joc 02.09.2016 в 11:45
source

1 answer

13

The behavior of the nextInt() It's not what you expect. When you input a 1714 you are actually entering a 1714 and a line break ( \n ) and the nextInt() does not consume the line break ( \n ).

That means that the nextLine() is reading this line break (which is empty -> \n ).

To solve it, when you do a nextInt() always put a nextLine() that will not have content.

From your code:

int i2    = scan.nextInt();
String saltoDeLinea = scan.nextLine();
String s2 = scan.nextLine();

Another way to solve it is to always read with nextLine() and do a cast a posteriori:

int i2 = Integer.parseInt(scan.nextLine());
String s2 = scan.nextLine();

In this answer from the original OS gives some more details, if you are interested.

    
answered by 02.09.2016 / 11:59
source