Skip to content
Advertisement

How to repeat an array together with a counter

What I’m trying to do with the following code is to print numbers and to replace the number with a word for the number that are divisible for 3, for 5 and for both 3 and 5. So, when the user starts the code, it has to choose how many players are going to play.

The problem is that my code print all the numbers from 1 to 100 four times, one time for every player. Can someone kindly explain me where is the mistake? Thanks!

Advertisement

Answer

Here are two solutions to that problem.

Option 1

In your case, there is no player object needed. So you could make use of a counter. That one will start by 1 and be incremented until it equals the selected number of players. Then you have to reset it to 1 again.

    int player = 1;
    for (int i = 1; i <= 100; i++) {
      if (i % 3 == 0 && i % 5 == 0) {
        System.out.println("player " + player + " says: divisible for 3 and 5");
      } else if (i % 3 == 0) {
        System.out.println("player " + player + " says: divisible for 3");
      } else if (i % 5 == 0) {
        System.out.println("player " + player + " says: divisible for 5");
      } else {
        System.out.println("player " + player + " says: " + i);
      }
      if (player < playersNumber) {
        player++;
      } else {
        player = 1;
      }
    }

Option 2

If you really need a player object, I will advise you to make use of a queue. Also therefore you do not need an extra for-loop.

final Queue<Integer> allPlayers = new LinkedList<>();
  for (int i = 1; i <= playersNumber; i++) {
    allPlayers.add(i);
  }

    for (int i = 1; i <= 100; i++) {
      final int player = allPlayers.poll();
      allPlayers.add(player);
      if (i % 3 == 0 && i % 5 == 0) {
        System.out.println("player " + player + " says: divisible for 3 and 5");
      } else if (i % 3 == 0) {
        System.out.println("player " + player + " says: divisible for 3");
      } else if (i % 5 == 0) {
        System.out.println("player " + player + " says: divisible for 5");
      } else {
        System.out.println("player " + player + " says: " + i);
      }
    }

Both solutions are not perfect, but there are working ones. If something is unclear with these solutions do not hesitate to ask me.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement