Nick Jones
Nick Jones

Reputation: 11

What is wrong with my for-loop?

public class Lockers {

    public static void main(String[] args) {
        boolean[] lockers = new boolean[100];
        int num = 2;
        for(int a=0; a < 100; a++) {
            lockers[a] = true;
        }

        for(int num=1; num < 101; num++) {

            for(int i=1; i < 100; i = i+num) {
                if (lockers[i]) {
                lockers[i] = false;
                    }
                else {
                    lockers[i] = true;
                    }
        }}

        for(int i=0; i < 100; i++) {
            if (lockers[i]) {
                System.out.print("Opened");
                }
            else {
                System.out.print("Closed");
                }
        }

}}

So this program is out of my java textbook for school, the idea is there are 100 lockers all open now starting at the second locker close every 2nd one. (2,4,6,8,10) Then restarting at the second locker go through with every 3rd locker doing the same (opening a closed locker, or closing an open one). Now my third for-loop seems to be my issue it will not function for some reason, the second for-loop is included so when the third for-loop starts it goes through every 2nd locker then back to the second for-loop statement it increases "num" by 1 goes through ever 3rd then 4th and so on and so forth. i would like to only use the basic commands i have learned so far in java and in the program now, so please help me solve this problem without really advanced coding.

The problem is that when i run the program the third for-loop is an infinite loop, i know the first two loops run fine, i tested that by after the second for-loop i made it output the "num" and it outputs all numbers 2 through 100 like i want but then the loop is endless at the third for-loop, not outputting anything else

Upvotes: 0

Views: 104

Answers (2)

Tomer_Zabo1802
Tomer_Zabo1802

Reputation: 11

I am not so good wtih java, so I will tell you what I think from my knowlage at C#.

In your last for loop you are writing i=i++, what you need to write is this: i=i+1

this is what i think .... try that tell me if that works for you

Upvotes: 1

Scorch
Scorch

Reputation: 83

Is it as simple as:

for(int i=0; i < 100; i = i++)

should be:

for(int i=0; i < 100; i++)

Upvotes: 1

Related Questions