Reputation: 41
public class OneHundredDoors
{
static OneHundredDoors.Door[] doors = new OneHundredDoors.Door[100];
static public class Door
{
public int doorClosed = 0;
public void open ()
{
this.doorClosed = 0;
}
public void close ()
{
this.doorClosed = 1;
}
private void printStatus (int address)
{
if (this.doorClosed == 0)
{
System.out.println("Door: " + address + " is Open!");
}
}
public void printStatusOfAll ()
{
for (int i = 0; i < doors.length; i++)
{
doors[i].printStatus(i);
}
}
public void passDoor (int increment)
{
for (int k = 0; k < doors.length; k += increment)
{
if (doors[k].doorClosed == 0)
{
doors[k].close();
}
else
{
doors[k].close();
}
}
}
}
public static void main (String [] args)
{
for (int i = 0; i < doors.length; i++)
{
doors[i] = new OneHundredDoors.Door ();
}
for (int j = 0; j < doors.length; j++)
{
doors[5].passDoor(j);
}
doors[5].printStatusOfAll();
}
}
My problem here is that the loop for doors[5].passDoor(j) simply does not work at all. No errors come up, neither at runtime or at compile time. Nothing happens. Leaving the program for a while and coming back to it does nothing, signifying that it is not doing anything in the background. Now this code solves the problem if you simply say doors[5].passDoor(2) then 3, then 4 up to 100. The problem is that that's a wasteful thing to do, and hence I instead want to do it with a for loop.
About the static array of objects: sorry about that, I'm doing that to make things easier in the testing stage, and will fix things when I've got it up and running (by making the array private to the class Door).
I'm only really posting this here because I'm at a complete loss for why this is happening. No errors to search for on the internet, no freezes so I know it's probably not an infinite (or long) loop, and no one seems to have similar problems with 100 doors (albeit this may be because they have not taken an object-oriented approach to it as I have done). Also, the code works completely fine if you type it 100 times as I have said (or at least, it APPEARS that it would do so had I the patience to actually type it out 100 times).
Note finally, that the loop here does not work for ANY value of x where j < x. (What I'm missing here must be something obvious and simple therefore).
Upvotes: 0
Views: 572
Reputation: 159754
The reason passDoor
won't work is that you pass an increment
of 0
to:
for (int k = 0; k < doors.length; k += increment) {
so the values of k
never increment causing an infinite loop.
Upvotes: 4