mazinAlmas
mazinAlmas

Reputation: 403

Using scanner in retrieving lines

am stuck with this question 6) Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, 789, the ENTER key. Analyze the following code.

Scanner scanner = new Scanner(System.in); 
int value = scanner.nextDouble();
int doubleValue = scanner.nextInt();
String line = scanner.nextLine();

i know the answer, the line will be equal to '\n' when the last statement is executed but why?

can anyone please explain it for me please?

Upvotes: 0

Views: 194

Answers (2)

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11950

Let's break this statement by statement.

Scanner scanner = new Scanner(System.in);
int value = scanner.nextDouble();

The system waits for you to type in the value.

34.3↲

The value is read as 34.3 but is truncated to 34 since it is stored as an integer. Now the next statement is executed.

int doubleValue = scanner.nextInt();

The system waits for you again to type in the value.

57.8↲

The value is read as 57 as you are using scanner.nextInt() and hence, the .8 is ignored. There is however a enter remaining in the buffer.

String line = scanner.nextLine();

The system now waits again for the input, and you type in this. The first new line is the remnant from the previous input.

↲
789↲

The scanner first sees the newline character, so it assumes that the line is terminated. So the value is read as \n

Hope this helps.

Upvotes: 1

Strikeskids
Strikeskids

Reputation: 4052

The Scanner reads as many tokens as necessary to get it's next output and then leaves all of the rest of the tokens there to be examined. nextInt() does not need the newline character so it leaves it in the token stream. When you call nextLine() it looks into the token stream, sees the newline character, and returns that.

Upvotes: 1

Related Questions