Java Getting values of 0 in Array

Let dissect your code to show you why this happens:

cups1[cup1]=balls; // #1
cup1++; // #2
balls++;
System.out.println(cups1[cup1]); // #3

Let’s assume that this is the first round, so cup1 is 1 and balls is 1.

  • Line #1: you assign the current value of balls (1) to cups1[1], cups1 now contains “0, 1, 0, 0, 0, 0, 0, 0, 0”
  • Line #2: you increment cup1, so cup1 is now 2
  • Line #3: you print out cups1[2], which still has it’s default value 0

By reordering the lines you will see the assigned numbers:

cups1[cup1]=balls;
System.out.println(cups1[cup1]);
cup1++;
balls++;

The complete code probably still doesn’t do what you want, but this is hard to tell…

Leave a Comment