在java中使用字符串输入退出do while循环

在java中使用字符串输入退出do while循环,java,Java,我试图编写以下代码,以便在输入E时允许连续抛硬币和退出。不确定DoWhile循环是否是连续执行的正确方法,或者我应该使用另一种方法 do { guess = sc.next(); tossGenerator(guess); }while(!guess.equals("E")||!guess.equals("e")); 那么,我是否因为无法跳出do循环或者应该使用不同的方法而错误地表达了代码。请帮忙。谢谢 将&&更改为|: } while (!guess.equals("

我试图编写以下代码,以便在输入E时允许连续抛硬币和退出。不确定DoWhile循环是否是连续执行的正确方法,或者我应该使用另一种方法

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")));
guess = sc.next();
while (!"e".equalsIgnoreCase(guess)) {
    tossGenerator(guess);
    guess = sc.next();
}
或者,您可以使用并消除:


退出条件应包括和操作员:

!guess.equals("E") && !guess.equals("e")
否则,任何
“E”
“E”
都会使其中至少一个变得微不足道,因为如果它是“E”,那么它就不是“E”,反之亦然。

将其更改为

while(!guess.equalsIgnoreCase("E") );

代码的一个问题是,即使
guess
是“e”,它也会调用
tossGenerator(guess)
。另一个是,
guess
总是不是“e”或“e”(不可能同时是两个)。我会这样写:

} while (!(guess.equals("E") || guess.equals("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);
}

签出-它有助于多个否定等。这需要在循环之前初始化
guess
,这可能是对代码的额外更改。