user2627736
user2627736

Reputation: 301

Java - ArrayIndexOutOfBounds while testing shows it's not

need some help with my code, it's giving me arrayindexoutofbounds 0 exception when I try to run it and it points to "results[counter]=random; " line, and the system.out.println line i wrote just before it correctly prints "Counter is 0 and numToss is 5 and random is 0(or 1)"

   public int[] results = new int[numToss];

   public void fillArray() {
      int counter = 0;
      //int[] results = new int[numToss];
      int random;
      while (counter < (numToss)) {
        if (Math.random() > 0.5) random = 1;
        else random = 0;
        System.out.println("Counter is " + counter + " and numToss is " + numToss + " and random is " + random);
        results[counter]=random; 
        counter++;
      }
   }

Upvotes: 0

Views: 50

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

arrayindexoutofbounds 0 exception

This can only mean one thing, that the results array has a size of 0.

Note that you are testing the value of numtoss when the fillArray method is called, and it's giving you a non-zero value, but this doesn't matter. No, what matters is its value when you create the results array, and numToss is likely zero when you create the results array.

Solution: make sure numToss has a meaningful non-zero value when you create the results array.


Edit
Perhaps you would like assign but not re-declare the variable to do this:

public void fillArray() {
   //int[] results = new int[numToss];
   results = new int[numToss];  // do not re-declare this variable!

   for (int counter = 0; counter < results.length; counter++) {
     results[counter] = (Math.random() > 0.5) ? 1 : 0; 
   }
}

Alternatively, you could re-declare the variable and have your method return the int array created.

public int[] fillArray() {
   int[] results = new int[numToss];

   for (int counter = 0; counter < results.length; counter++) {
     results[counter] = (Math.random() > 0.5) ? 1 : 0; 
   }
   return results;
}

Note: this is one reason why you should use a for loop when iterating through an array as this totally avoids ArrayIndexOutOfBoundsExceptions.

Also, since your results array appears to only hold 2 values, consider making it an array of booleans and not ints.

Upvotes: 2

Related Questions