2012-01-01 12 views
0

拡張forループfor(int cell:locationCells)を通常のforループに切り替える手助けができますか?なぜコードにbreak;があるのですか?ありがとうございました!拡張forループを通常の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

ループが止まるように '休憩 'があります。私はなぜあなたが配列を反復できないのかを理解することに問題があると思う - これまで何を試したことがありますか? –

答えて

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ステートメントは、ループを「中断する」、またはループから抜け出すために使用されます。これにより、ループ文が停止します。