user133466
user133466

Reputation: 3415

Translating an enhanced for loop into regular for loop

Can someone help me turn the enhanced for loop for(int cell:locationCells) to a regular for loop? And why is there a break; in the code? Thank you!

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

        }
    }

}

Upvotes: 0

Views: 1252

Answers (2)

Shawn Janas
Shawn Janas

Reputation: 2733

You are going to want to use the following.

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

The break statements is used to 'break' or exit out of the loop. This will stop the looping statement.

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234807

The traditional for loop version is:

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

The break stops the loop and transfers control to the statement following the loop (that is, to if(numOfHits...)

Upvotes: 2

Related Questions