That would suggest that cells
is empty. If it's not, we're just guessing - please post a complete program.
However, I would strongly urge you to add braces around your if
statement1:
public void assignCell()
{
Prisoner prisoner = prisoners.get(id-1);
for(Cell cell : cells)
{
if(cell.isAvailable())
{
cell.allocate(prisoner);
String bunk = null;
if(cell.isEven())
{
bunk = "top bunk of cell";
}
else
{
bunk = "only bunk of cell";
}
System.out.println("\t\t" + prisoner.nameToString()
+ " is in the " + bunk + cell);
}
}
}
In fact, I'd then try to reduce the nesting, and use the conditional operator too:
public void assignCell()
{
Prisoner prisoner = prisoners.get(id-1);
for(Cell cell : cells)
{
if(!cell.isAvailable())
{
continue;
}
cell.allocate(prisoner);
String bunk = cell.isEven() ? "top bunk of cell" : "bottom bunk of cell";
System.out.println("\t\t" + prisoner.nameToString()
+ " is in the " + bunk + cell);
}
}
Oh, and you probably want a return
or break
statement there, otherwise a single prisoner will be assigned to all the available cells. Indeed, that may be happening with your first prisoner: check the output of the program very carefully!
1 Another alternative is just to indent the if
statement - but give some indication that you really did mean the if
statement to be in the loop. Personally I find it helpful always to use braces, as then you can't accidentally add another statement after the first one which looks like it would be part of the loop, but isn't. Readability is king, IMO.