当我运行我的代码时,它总是停在for循环并跳过它.
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.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能解决这个问题呢?
这表明这cells是空的.如果不是,我们只是猜测 - 请发布一个完整的程序.
但是,我强烈建议您在if声明1周围添加大括号:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
事实上,我会尝试减少嵌套,并使用条件运算符:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
哦,你可能想要一个return或break声明,否则将为所有可用的单元分配一个囚犯.事实上,你的第一个囚犯可能会发生这种情况:仔细检查计划的输出!
1另一个替代方法是缩进if语句 - 但是给出一些迹象表明你确实意味着if语句在循环中.我个人觉得总是使用大括号是有帮助的,因为你不能在第一个看起来像循环的一部分之后不小心添加另一个语句,但事实并非如此.可读性是国王,国际海事组织.