2

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.

1
  • 3
    Check out DeMorgan's Law - it helps with multiple negations etc. Commented Nov 21, 2012 at 17:17

4 Answers 4

8

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

This requires guess to be initialized prior to the loop, which may be an additional change to the code.
3

Change it to

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

Comments

2

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.

Comments

1

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.