I was trying to write the following code to allow continuous coin toss and exits when E is entered. Not sure if do-while loop is the correct way to do it continuously or i should use another method.
do {
guess = sc.next();
tossGenerator(guess);
}while(!guess.equals("E")||!guess.equals("e"));
So, did I phrase the code wrongly because I can't get out of the do loop or a different method should be used. Please help. Thanks.
Change &&
to ||
:
} while (!guess.equals("E") && !guess.equals("e"));
Or rearrange it like this:
} while (!(guess.equals("E") || guess.equals("e")));
Alternatively you can use String.equalsIgnoreCase()
and eliminate the conjunction :
} while (!guess.equalsIgnoreCase("e"));
将其更改为
while(!guess.equalsIgnoreCase("E") );
The exit condition should be with AND operator:
!guess.equals("E") && !guess.equals("e")
otherwise any "E"
or "e"
would make trivially true at least one of them because if it's "e" then it's not "E" and viceversa.
One problem with your code is that it will call tossGenerator(guess)
even when guess
is "e". Another is that guess
is always going to be not "e" or not "E" (it can't be both at the same time). I'd write it like this:
guess = sc.next();
while (!"e".equalsIgnoreCase(guess)) {
tossGenerator(guess);
guess = sc.next();
}
Alternatively, use a for
loop:
for (guess = sc.next(); !"e".equalsIgnoreCase(guess); guess = sc.next()) {
tossGenerator(guess);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.