Better way to read nextLine [duplicate]

0 votes
asked Feb 9, 2017 by tyler-poland

This question already has an answer here:

  • Using scanner.nextLine() [duplicate] 5 answers

1 Answer

+1 vote
answered Nov 29 by elliott-frisch

Operate on lines at a time, then you don't need to worry about the nextDouble() (or nextInt()) calls leaving a trailing newline. Like,

Scanner scan = new Scanner(System.in);
int i = Integer.parseInt(scan.nextLine());
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();

If, you want to allow the int and double to be on the same line then you could do

Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = Double.parseDouble(scan.nextLine());
String s = scan.nextLine();

But without knowing your input format, that may or not be helpful. I would prefer the version most readable for the problem at hand (parsing the input).

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...