Перевод расширенного цикла for в обычный цикл for - PullRequest
0 голосов
/ 01 января 2012

Может кто-нибудь помочь мне превратить расширенный цикл 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 ]

2 голосов
/ 01 января 2012

Вы захотите использовать следующее.

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

Операторы break используются для «разрыва» или выхода из цикла.Это остановит зацикливание оператора.

2 голосов
/ 01 января 2012

Традиционная версия петли for:

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

break останавливает цикл и передает управление оператору, следующему за циклом (то есть if(numOfHits...)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...