首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么scan.next() + scan.nextLine()而不是scan.nextLine()

为什么scan.next() + scan.nextLine()而不是scan.nextLine()
EN

Stack Overflow用户
提问于 2019-02-14 13:56:33
回答 2查看 576关注 0票数 0

在以下方面有何区别:

代码语言:javascript
复制
String s2 = scan.nextLine(); 

代码语言:javascript
复制
String s2 = scan.next() + scan.nextLine(); 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-14 14:13:10

注册表。扫描器javadoc

next() -从这个扫描器中查找并返回下一个完整的令牌。 nextLine() --将此扫描器移过当前行,并返回跳过的输入。

因此,使用next(),它只读取第一个单词,只读取第一个令牌(字符串)(剩余的东西存储在缓冲区中,但是nextLine()允许您读取,直到enter是pressed=全行。

如果你试着跟随片段,尝试把单词和句子组合起来,就会发现不同的地方:

代码语言:javascript
复制
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 +"'");
}

投入和产出:

代码语言:javascript
复制
first input:
firstWord
tmp: 'firstWord'
second input:
second sentence
2nd tmp: 'second sentence'
//-------------
first input:
first sentencemorewords
tmp: 'first'
second input:
2nd tmp: 'sentencemorewords'

也许更好的解释来自于直接打印:

代码语言:javascript
复制
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处理。

代码语言:javascript
复制
first input:
first second third more words
tmp: 'first'
second input:
next: second,... nextLine:  third more words

因此,在您的程序中,如果只需要一个单词,则使用sc.next()**,,如果需要阅读整行,请使用** nextLine()

票数 0
EN

Stack Overflow用户

发布于 2019-02-14 14:05:33

试试下面的代码片段:

代码语言:javascript
复制
    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); 

投入+产出:

代码语言:javascript
复制
//Input
hello <enter pressed here>
world <enter pressed here>
//Output
scanner.nextLine(): hello
scanner.next()+ scanner.nextLine(): world

nextLine()方法使用缓冲输入读取用户输入的字符串。缓冲输入意味着允许用户备份并更改字符串,直到用户点击Enter键--在本例中,这将返回第一个输入的number.The next ()方法,并从扫描仪返回下一个完整的令牌,即在这种情况下将返回最后一个输入值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54692126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档