2016-12-04 290 views
0

所以我創建了一個方法,使用多個for循環,我正在尋找一種方法,我可以讓前面的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()方法中打印出所有的數據,所以我在想,如果有一個我可以停止以前的循環運行,打印出我的聲明並開始下一個?任何幫助表示讚賞,謝謝。

+1

是不是因爲你封閉在第一個第二循環? – GurV

+0

那是因爲那個。 – Ben

回答

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. 
} 
+0

啊我明白了,謝謝你的幫助。 – Ben

0

您可以使用break語句停止for循環。 在callgo.goShower()之後調用此break語句,循環將中斷,導致在for循環結束後執行下一個語句大括號(}) callgo.goShower(); 休息;