为什么扫描仪会以这种方式运行?

时间:2015-04-02 06:53:48

标签: java java.util.scanner

我只是好奇:

假设我设置了扫描仪。

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个字符串,它就不会做它看起来的样子。

我知道周围的工作是在两者之间留一个空白,但我想知道为什么会发生这种情况。

2 个答案:

答案 0 :(得分:3)

sc.nextLine()读取当前行,直到遇到行尾字符。如果在调用读取部分行(sc.nextLine()nextInt()等...)的扫描程序方法后调用next(),则会返回当前行的结尾(如果当前行剩下的所有内容都是新行字符,则可能为空。

因此,在您从部分行读取输入后,如果要阅读下一行输入,则必须先调用sc.nextLine()以移过当前行,然后再将sc.nextLine()分配给获取下一行内容的变量。

答案 1 :(得分: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()将不会打印任何内容并跳转到下一行。