Java input problem

Asked

Viewed 83 times

3

The inputs of my program are overwriting itself. It ignores the first and already Lanca 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 get around this error?

  • The variable in is of class Scanner?

  • Yeah, that’s the one

1 answer

5


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

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

in.nextLine();
String nome = in.nextLine();

Another option is to change your code to always use in.nextLine() and make the Casts manually, so that never over a line break in the input.

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

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

  • Excellent as well :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.