2015-04-02 77 views
0

我只是好奇:扫描仪为何如此操作?

假设我设置了扫描仪。

Scanner sc = new Scanner (System.in) 
int number = sc.nextInt(); 
String name = sc.nextLine(); 
System.out.println (number); 
System.out.println (name); 

会发生什么事情,我甚至不会输入名称,所有打印的数字都是数字。相反,如果我这样做:

Scanner sc = new Scanner (System.in) 
int number = sc.nextInt(); 
String name = sc.next(); 
System.out.println (number); 
System.out.println (name); 

然后,一切工作顺利,但不能在字符串中使用空格。

为什么被扫描的字符串在被一个数字后面显得很滑稽。如果我只是使用2个字符串,它不会做它看起来。

我知道解决的办法是在两者之间放一条空白线,但我只想知道为什么发生这种情况。

+0

难道你不把“空间”与“新行”字符混淆? – zubergu 2015-04-02 06:56:06

+0

你的困惑可能是'next()'和'nextLine()'? – Prashant 2015-04-02 06:57:48

+0

不,我不是。如果我想用第二个例子写出字符串“This blows”,那么所有打印的内容都是This。 – 2015-04-02 06:59:07

回答

3

sc.nextLine()读取当前行,直到遇到行尾字符。如果在调用读取部分行的扫描器方法(nextInt(),next()等)之后调用sc.nextLine(),它将返回当前行的结尾(如果当前行的所有行结束,则可能为空)是新行字符)。

因此,从部分行读取输入后,如果你想读取输入的下一行,必须先调用sc.nextLine()搬过去的当前行,然后才分配sc.nextLine()一个变量来获取内容下一行。

+0

我明白了!有趣。感谢您的澄清。我只是好奇,我知道如何解决它,但不知道为什么我必须。 – 2015-04-02 07:02:17

1

我完全同意@Eran的回答,只是想指出,通常那种信息就在javadoc中,你只需要阅读它。

nextInt()

* Scans the next token of the input as an <tt>int</tt>. 
* This method will throw <code>InputMismatchException</code> 
* if the next token cannot be translated into a valid int value as 
* described below. If the translation is successful, the scanner advances 
* past the input that matched. 

正如你可以看到它并没有说明跳跃到下一行任何东西,它停留在同一行。

对于nextLine()

* Advances this scanner past the current line and returns the input 
* that was skipped. 
* 
* This method returns the rest of the current line, excluding any line 
* separator at the end. The position is set to the beginning of the next 
* line. 

所以调用nextInt()后你仍然在同一行,如果没有什么更多的则nextLine()将只打印什么,并跳转到下一行。