Reputation: 21
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.
Upvotes: 2
Views: 1683
Reputation: 361585
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"));
Upvotes: 8
Reputation: 234795
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);
}
Upvotes: 1
Reputation: 133567
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.
Upvotes: 2