user1745508
user1745508

Reputation: 45

How to exclude zero in a for loop in Java

I'm trying to exclude the zero in this nested for loop here using != 0; but it is not doing anything. I'm trying to get the probability of each out come of 2 six sided dice when rolled. I must figure out the amount of times they are rolled first, but a die doesn't have a zero in it, so I must exclude it. I can't figure out why this doesn't work.

for( die2 = 0; die2 <= 6 && die2 != 0; die2++)
            for( die1 = 0; die1 <= 6 && die1 != 0; die1++)
                System.out.println("Die 2: " + (die2 * userInputValue) + " " + "Die 1: " +       (die1 * userInputValue));

Upvotes: 1

Views: 1759

Answers (2)

Adam Mihalcin
Adam Mihalcin

Reputation: 14468

You should start your loops at 1, not at 0.

Let's look at your current code:

for (die2 = 0; die2 <= 6 && die2 != 0; die2++)
    for (die1 = 0; die1 <= 6 && die1 != 0; die1++)
        // Do something

Why aren't you hitting the do something line? This chunk of code is equivalent(*) to

die2 = 0;
while (die2 <= 6 && die2 != 0) {
    die1 = 0;
    while (die1 <= 6 && die1 != 0) {
        // Do something
        die1++;
    }
    die2++;
}

Notice that the first condition check if die2 is 0, but die2 will always be 0 upon entering the loop because that's what you set. Instead, you should use

for (die2 = 1; die2 <= 6; die2++)
    for (die1 = 1; die1 <= 6; die1++)
        // Do something

which will skip 0 because you never set die2 or die1 to 0 in the first place.


(*) This rewriting of a while loop isn't exactly equivalent to a for loop, because this rewriting doesn't preserve the semantics of the continue statement, but your code doesn't use continue, so in this case it's equivalent to the original.

Upvotes: 2

kosa
kosa

Reputation: 66657

Just start loop from 1 instead of 0

for(int die2 = 1; die2 <= 6 ; die2++)
            for(int die1 = 1; die1 <= 6 ; die1++)
                System.out.println("Die 2: " + (die2 * userInputValue) + " " + "Die 1: " +       (die1 * userInputValue));

Upvotes: 2

Related Questions