Answer the question
In order to leave comments, you need to log in
Why is the increment by one in the break loop placed at the end, and in the loop with continue at the beginning?
There are two codes
String players[] = {"David", "Daniel", "Anna", "Gregory"};
int totalPlayers = players.length;
int counter =0;
while (counter< totalPlayers){
if (counter == 3){
break;
}
String thePlayer = players[counter];
System.out.println("While-Break Congratulations, "+thePlayer+ "!");
counter++;
}
String players[] = {"David", "Daniel", "Anna", "Gregory"};
int totalPlayers = players.length;
int counter=0;
while (counter < totalPlayers){
counter++;
String thePlayer = players[counter];
if (thePlayer.equals("David")){
continue;
}
System.out.println("While equals Congratulations, "+ thePlayer+ "!");
}
Answer the question
In order to leave comments, you need to log in
Because the code does different things.
In the first case, the first 3 people will receive congratulations, and then break will throw us out of the loop.
In the second case, by incrementing counter , we skip "David" and congratulate the last 3 people, while falling into ArrayIndexOutOfBound due to the fact that we first incremented counter , and then tried to take an element array with index 4.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question