英文:
Can't get program to break on specific string
问题
代码大部分都能正常运行,但是如果我输入"No way",它仍然会停止循环。我应该以不同的方式设置它,还是使用一个长度函数?我搜索的所有关于如何中断循环的内容都是使用整数。
请参见下面的代码:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("继续吗?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("不")){
break;
}
}
}
}
英文:
The code works for the most part, but if I type "No way" it still stops the loop. Should I set it up a different way or use a length function ? Everything I've searched on breaking a loop used integers.
See the code below:
import java.util.Scanner;
public class CarryOn {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.next());
if (answer.equalsIgnoreCase("no")){
break;
}
}
}
}
答案1
得分: 2
只读取一个标记。 "No way" 是两个标记:"No" 和 "way"。
如果要读取整行,请改用 scanner.nextLine()
。
英文:
scanner.next()
only reads a single token. No way
is two tokens: No
and way
.
Use scanner.nextLine()
instead, if you want to read the whole line.
答案2
得分: 2
在这种情况下,只使用.next
会将“no”存储在“no way”中。请改用.nextLine
:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
输出:
Shall we carry on?
no way
Shall we carry on?
no
查看这个帖子获取更多信息。
英文:
Using .next
in this case only stores "no" in "no way". Use .nextLine
instead:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Shall we carry on?");
String answer = String.valueOf(scanner.nextLine());
if (answer.equalsIgnoreCase("no")){
break;
}
}
Output:
Shall we carry on?
no way
Shall we carry on?
no
Check this post for more information.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论