无法在特定字符串上中断程序。

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月5日 04:52:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63254870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定