M
M
Mr Mojito2018-08-30 12:56:04
Java
Mr Mojito, 2018-08-30 12:56:04

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

and
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+ "!");
        }

Why is the counter++ operation in the first code snippet; goes at the end of the cycle, and in the second at the beginning?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Osipov, 2018-08-30
@replicate

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 question

Ask a Question

731 491 924 answers to any question