Problem with input java


My program inputs are overwriting. He ignores the first one and already launches the second straight.

System.out.println("Digite o nome do passageiro");
String nome = in.nextLine();
System.out.println("Digite o numero do ticket do passageiro");
int ticket = in.nextInt();

How to work around this error?

asked by anonymous 19.11.2015 / 21:29

1 answer


This happens because methods such as nextInt , and next do not consume the input line break. When you call nextLine the method finds the line break and assumes that the entry is empty.

One way to fix the problem is to discard the first line break before reading the name:

String nome = in.nextLine();

Another option is to change your code to always use in.nextLine() and do the casts manually, so never over a line break in the entry.

int ticket = Integer.parseInt(in.nextLine());

Reference : SOen - Skipping nextLine () after using next (), nextInt () or other nextFoo () methods

19.11.2015 / 21:36