2012-01-01 132 views
0

有人可以幫助我將增強型for循環for(int cell:locationCells)轉換爲常規for循環嗎?爲什麼代碼中有break;?謝謝!將增強型for循環轉換爲循環常規

public class SimpleDotCom { 

    int[] locationCells; 
    int numOfHits = 0 ; 

    public void setLocationCells(int[] locs){ 
     locationCells = locs; 
    } 

    public String checkYourself(int stringGuess){ 
     int guess = stringGuess; 
     String result = "miss"; 

     for(int cell:locationCells){ 
      if(guess==cell){ 
       result ="hit"; 
       numOfHits++; 
       break; 
      } 
     } 
     if(numOfHits == locationCells.length){ 
      result ="kill"; 
     } 
     System.out.println(result); 
     return result; 
    } 
} 



public class main { 

    public static void main(String[] args) { 

     int counter=1; 
     SimpleDotCom dot = new SimpleDotCom(); 
     int randomNum = (int)(Math.random()*10); 
     int[] locations = {randomNum,randomNum+1,randomNum+2}; 
     dot.setLocationCells(locations); 
     boolean isAlive = true; 

     while(isAlive == true){ 
      System.out.println("attempt #: " + counter); 
      int guess = (int) (Math.random()*10); 
      String result = dot.checkYourself(guess); 
      counter++; 
      if(result.equals("kill")){ 
       isAlive= false; 
       System.out.println("attempt #" + counter); 
      } 

     } 
    } 

} 
+0

有一個'break',所以它停止循環。我想我有問題,理解爲什麼你不能遍歷數組 - 你到目前爲止嘗試過什麼? – 2012-01-01 01:39:04

回答

2

傳統for循環的版本是:

for (int i = 0; i < locationCells.length; ++i) { 
    int cell = locationCells[i]; 
    if (guess==cell){ 
     result ="hit"; 
     numOfHits++; 
     break; 
    } 
} 

break停止循環,並將控制轉移到循環(即,if(numOfHits...

2

你將後面的語句想要使用以下內容。

for(int i = 0; i < locationCells.length; i++) { 
    if(guess == locationCells[i]) { 
     result = "hit"; 
     numHits++; 
     break; 
    } 
} 

break語句用於'break'或退出循環。這將停止循環語句。