[英]Exiting do-while loop with string input in java
我试图写下面的代码,以便在输入E时允许连续抛硬币并退出。 不确定do-while循环是否是连续执行的正确方法,或者我应该使用其他方法。
do {
guess = sc.next();
tossGenerator(guess);
}while(!guess.equals("E")||!guess.equals("e"));
所以,我是否错误地使用了代码,因为我无法摆脱do循环或者应该使用不同的方法。 请帮忙。 谢谢。
将&&
更改为||
:
} while (!guess.equals("E") && !guess.equals("e"));
或者像这样重新排列:
} while (!(guess.equals("E") || guess.equals("e")));
或者,您可以使用String.equalsIgnoreCase()
并消除连接 :
} while (!guess.equalsIgnoreCase("e"));
将其更改为
while(!guess.equalsIgnoreCase("E") );
退出条件应该是AND运算符:
!guess.equals("E") && !guess.equals("e")
否则任何"E"
或"e"
都至少会使其中一个真实,因为如果它是“e”那么它不是“E”而反之亦然。
您的代码的一个问题是,即使guess
为“e”,它也会调用tossGenerator(guess)
。 另一个是guess
总是不是“e”或不是“E”(它不能同时出现)。 我写的是这样的:
guess = sc.next();
while (!"e".equalsIgnoreCase(guess)) {
tossGenerator(guess);
guess = sc.next();
}
或者,使用for
循环:
for (guess = sc.next(); !"e".equalsIgnoreCase(guess); guess = sc.next()) {
tossGenerator(guess);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.