[英]How to manually exit a while loop (java)
该代码将从控制台获取用户输入,并根据输入是否为Integer转到两个位置之一。 该例外被捕获,然后处理再次阅读它把它弄出来的流。 (不确定Scanner是否算作流,但是我知道没有input.next()它将永远不会离开该部分)。
因此,我想知道的是,如果使用特定输入到达MismatchException,如何退出循环。 我测试过,如果(bad_input ==任何东西),它原来我从来没有真正到达那里。 我在该块中尝试了一些从未执行过的打印语句。 将不胜感激。
解决了
不知道如何关闭的问题,但是这已经解决了。 我错误地使用==检查两个字符串。 正确的方法是使用bad_input.equals(“X”)。
public static void main(String[] args){
//read input from console
Scanner input = new Scanner(System.in);
boolean loop = true;
while(loop){
//inputting "1 2 d 1" will evaluate each term separately and output at once
try{
//choice = console input only in INTEGER
int choice = input.nextInt();
System.out.println("Input was " + choice);
} catch (InputMismatchException ex){
//here if input != INTEGER
String bad_input = input.next();
System.out.println("Bad Input: " + bad_input);
//need to figure out how to exit loop!!
if(bad_input == "x"){
loop = false;
return;
}
continue;
}
}
}
在java中,字符串比较使用的是equals函数“ ==”可能不起作用
更改
if (bad_input == "x") {
loop = false;
return;
}
至
if (bad_input.equals("x")) {
loop = false;
return;
}
尝试使用break。
if(condition)
break;
break;
将立即退出循环。 不过,您正在执行的操作也应该起作用。 我不确定您是否需要if
语句,仅当输入不是整数时,才会执行整个catch块。
好吧,我认为你需要使用
if(bad_input.equals("x")){
loop = false;
return;
}
==检查相同的参考
.equals检查相同的值
可能是您应该使用equalsIgnoreCase方法。
if (bad_input.equalsIgnoreCase("x")) {
而要以除整数之外的任何其他值退出循环,只需使用break即可 。
catch (InputMismatchException ex) {
// here if input != INTEGER
String bad_input = input.next();
System.out.println("Bad Input: " + bad_input);
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.