简体   繁体   English

在扫描仪中使用扫描仪

[英]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. 6)假设您输入34.3,ENTER键,57.8,ENTER键,789,ENTER键。 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? 我知道答案,当执行最后一条语句时,该行将等于“ \\ n”,但为什么呢?

can anyone please explain it for me please? 谁能为我解释一下吗?

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. nextInt()不需要换行符,因此将其留在令牌流中。 When you call nextLine() it looks into the token stream, sees the newline character, and returns that. 当您调用nextLine()它将查看令牌流,看到换行符,然后将其返回。

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. 该值读取为34.3,但由于将其存储为整数,因此被截断为34。 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. 当您使用scanner.nextInt() ,该值读取为57,因此,.8被忽略。 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 因此该值读取为\\ n

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM