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