java 如果用户输入特殊字符,如何停止 while 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26545604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:07:15  来源:igfitidea点击:

How to stop a while loop if the user entered a special character

java

提问by Parisa

I'm writing a program in java and I'm getting some numbers from the user and I wanna say if the user entered '#' exit the while loop. Any help is appreciated.

我正在用 java 编写一个程序,我从用户那里得到了一些数字,我想说如果用户输入了 '#' 退出 while 循环。任何帮助表示赞赏。

回答by Olavi Mustanoja

After you have gotten the user input, you can see if the input equals "#" like so:

获得用户输入后,您可以查看输入是否等于“#”,如下所示:

input.equals("#");

You can get the user input using Scanner:

您可以使用 Scanner 获取用户输入:

Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();

You can break from a loop by using break.

您可以使用 break 来中断循环。

The while loop would look like this:

while 循环如下所示:

while (true) {
    String input = scanner.nextLine();
    if (input.equals("#")) {
        break;
    }

    int number = Integer.parseInt(input);
    // do stuff
}

回答by MadsDue

Use break to stop your loop

使用 break 停止循环

string userInput = "sdfss £sdf";

while(true)
{
   if(userInput.matches("[^ \w]"))
   {
     break;
   }
}

回答by Malith Pamuditha Fernando

I use while loop here to terminate if user enter -1 and get the total of user input numbers

如果用户输入 -1 并获取用户输入数字的总数,我在这里使用 while 循环来终止

while(true){
    System.out.print("Input the number  :"); 
    int number = input.nextInt();
    if(number >=0)
    total += number;
    if(number == -1)
        break;
}

System.out.println("Total: " + total);

回答by Klaus Byskov Pedersen

To terminate any kind of loop, you use a breakstatement.

要终止任何类型的循环,请使用breakstatement

回答by Borja Coalla

Scanner scanner = new Scanner(System.in);
String entrada="a";
while(!entrada.equals("#")){
        System.out.println("hola");
        entrada = scanner.nextLine();
}