[英]Using a Scanner, how do I collect all of the input that I enter?
Scanner input = new Scanner(System.in);
boolean flag = true;
System.out.print("What is your name? ");
flag = true;
while(flag == true){
name = input.next();
fullName = fullName + " " + name;
if(input.hasNext() == false){
flag = false;
}
}
The above code is just a sample of my whole program, but this piece of the code is where I am having problems. 上面的代码只是我整个程序的示例,但是这段代码正是我遇到问题的地方。
With the above code, the input that I enter into the console is "the one"
. 使用上面的代码,我输入到控制台的输入为
"the one"
。 The problem is after input.next()
collects "one"
and then adds it to fullName
, when the code goes to the if statement to check if there is more input (which there is none), the program just hangs. 问题出在
input.next()
收集"one"
然后将其添加到fullName
,当代码进入if语句以检查是否有更多输入(没有输入)时,程序只是挂起。 I am using BlueJ
and the program debugger says that the thread is still running but nothing is going on. 我正在使用
BlueJ
,程序调试器说该线程仍在运行,但没有任何反应。 I'm wondering how do I collect the entire input of "the one"
using a Scanner
? 我想知道如何使用
Scanner
收集"the one"
的全部输入?
I suggest you to use 我建议你用
if(!input.hasNext()){
flag = false;
}
Rather than using 而不是使用
if(input.hasNext() == false){
flag = false;
}
Use name = input.nextLine();
使用
name = input.nextLine();
Refer: What's the difference between next() and nextLine() methods from Scanner class? 请参阅: Scanner类的next()和nextLine()方法之间有什么区别?
next() Finds and returns the next complete token from this scanner.
next()查找并返回此扫描器的下一个完整令牌。
nextLine() Advances this scanner past the current line and returns the input that was skipped.
nextLine()将此扫描程序前进到当前行之外,并返回跳过的输入。
while (true) {
name = input.nextLine();
if(name.length() == 0){
break;
}
fullName = fullName + " " + name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.