所以我创建了一个使用多个for循环的方法,我正在寻找一种方法,我可以让前一个for循环停止运行,这样我就可以开始使用下一个了。这是我的代码:
public void timePasses()
{
House callgo = new House();
System.out.println("Shower usage:\n");
for (int x = 0; x < 4; x++)
{
callgo.goShower();
//Need to stop here, System.out.println("Cooker usage:\n"); only needs to print once.
System.out.println("Cooker usage:\n");
for (int z = 0; z < 4; z++)
{
callgo.goCooker();
}
//this method is called as part of the simulation to trigger a new fifteen minute period
//in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.
}
}
我知道可以使用多种方法但是对于规范,我需要在一个timePasses()
方法中打印出所有数据,所以我想知道是否有办法可以阻止前面的循环运行,打印出我的声明并开始下一个?感谢任何帮助。谢谢。
答案 0 :(得分:1)
我想你想要这个:
public void timePasses()
{
House callgo = new House();
System.out.println("Shower usage:\n");
for (int x = 0; x < 4; x++)
{
callgo.goShower();
//Need to stop here, System.out.println("Cooker usage:\n"); only needs to print once.
}
System.out.println("Cooker usage:\n");
for (int z = 0; z < 4; z++)
{
callgo.goCooker();
}
//this method is called as part of the simulation to trigger a new fifteen minute period
//in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.
}
答案 1 :(得分:0)
您可以使用break语句停止for循环。 在callgo.goShower()之后调用此break语句,并且循环将中断导致在循环结束后执行下一个语句大括号(}) callgo.goShower(); 休息;