views:

28

answers:

3

Okay, so I'm trying to learn how to use the % operator, and I made a simple program that prints out [0] in a loop, and every ten times it goes to the next line, but the first time it doesn't.

this is the output:

[0][0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0]

this is what the output should be:

[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]

And this is the code:

public class RemainderLoop {
    public static void main(String[] args) {
        for(int i = 0; i < 50; i++){
            System.out.print("[0]");

            if((i%10) == 0 && i > 0)
                System.out.print("\n");
        }
    }
}
+4  A: 

Notice that you're starting your counter, i, at zero, not at one. Do a few loops by hand, and you'll soon see the error. Any more than that, and I'd give the answer away.

Lord Torgamus
That's good advice in general..should always run it through in your head (or on paper) if there's a problem.
Mark
A: 

try this..

public class RemainderLoop { public static void main(String[] args) { for(int i = 1; i <= 50; i++){ System.out.print("[0]");

        if((i%10) == 0 && i > 0)
            System.out.print("\n");
    }
}

}

william
+1  A: 

basically, since you are printing the newline AFTER you print the [0], when you get to the 11th item, you print it before the newline, when you want to print it after, because its the 11th.

try this instead

public class Loop {
    public static void main(String[] args) {
        for(int i = 0; i < 50; i++){
            if((i%10 == 0) && i > 0)
                System.out.print("\n");
            System.out.print("[0]");
        }
    }
}

or

public class Loop {
    public static void main(String[] args) {
        for(int i = 1; i < 51; i++){
            System.out.print("[0]");

            if((i%10 == 0) && i > 0)
                System.out.print("\n");
        }
    }
}
hvgotcodes