在以下方面有何区别:
String s2 = scan.nextLine(); 和
String s2 = scan.next() + scan.nextLine(); 发布于 2019-02-14 14:13:10
注册表。扫描器javadoc
next()-从这个扫描器中查找并返回下一个完整的令牌。nextLine()--将此扫描器移过当前行,并返回跳过的输入。
因此,使用next(),它只读取第一个单词,只读取第一个令牌(字符串)(剩余的东西存储在缓冲区中,但是nextLine()允许您读取,直到enter是pressed=全行。
如果你试着跟随片段,尝试把单词和句子组合起来,就会发现不同的地方:
Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
tmp = sc.next() + sc.nextLine();
System.out.println("2nd tmp: '" + tmp +"'");
}投入和产出:
first input:
firstWord
tmp: 'firstWord'
second input:
second sentence
2nd tmp: 'second sentence'
//-------------
first input:
first sentencemorewords
tmp: 'first'
second input:
2nd tmp: 'sentencemorewords'也许更好的解释来自于直接打印:
Scanner sc = new Scanner(System.in);
System.out.println("first input:");
String tmp = sc.next();
System.out.println("tmp: '" + tmp +"'");
System.out.println("second input:");
System.out.println("next: " + sc.next() +",... nextLine: " + sc.nextLine());请注意,只有第一个单词由第一个
sc.next()处理,如果有更多的单词,任何其他单词都将由第二个sc.next()处理,但如果超过2个单词,则剩余的字符串将由nextLine处理。
first input:
first second third more words
tmp: 'first'
second input:
next: second,... nextLine: third more words因此,在您的程序中,如果只需要一个单词,则使用
sc.next()**,,如果需要阅读整行,请使用**nextLine()
发布于 2019-02-14 14:05:33
试试下面的代码片段:
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String s2 = scanner.next()+ scanner.nextLine();
System.out.println("scanner.nextLine(): "+ s);
System.out.println("scanner.next()+ scanner.nextLine(): " + s2); 投入+产出:
//Input
hello <enter pressed here>
world <enter pressed here>
//Output
scanner.nextLine(): hello
scanner.next()+ scanner.nextLine(): worldnextLine()方法使用缓冲输入读取用户输入的字符串。缓冲输入意味着允许用户备份并更改字符串,直到用户点击Enter键--在本例中,这将返回第一个输入的number.The next ()方法,并从扫描仪返回下一个完整的令牌,即在这种情况下将返回最后一个输入值。
https://stackoverflow.com/questions/54692126
复制相似问题