将增强的for循环转换为常规for循环

时间:2012-01-01 01:37:17

标签: java for-loop

有人可以帮助我将增强型for循环for(int cell:locationCells)转换为常规for循环吗?为什么代码中有break;?谢谢!

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);
            }

        }
    }

}

2 个答案:

答案 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...

答案 1 :(得分:2)

您将要使用以下内容。

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

break语句用于“中断”或退出循环。这将停止循环语句。