0

I am having some trouble with an assignment. The point is to create a program which will generate a random number between 0 and 1, and then if it is heads save "h" to the next free space in an array, and if it is tails save "s". The problem is when I run the program it gives me an error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2" because (I think) it keeps on going after it has reached the end of the array, can anybody help?

import java.util.Random;
public class CoinToss{

   public int heads;
   public int tails;
   public int totalToss;
   public int arraySize;
   public int numOfTails = 0;
   public int numOfHeads = 0;
   public String [] array = new String[arraySize];

   public CoinToss(int NumberOfTosses) {
      arraySize = NumberOfTosses;
   }

   public int getHeads() {
      return heads;
   }

   public int getTails() {
      return tails;
   }

   public int totalTosses() {
      return totalToss;
   }

   public void tossCoin() {
      for (int i = 0; i <= arraySize; i++) {
         double randomNumber = Math.random();

         if (randomNumber < 0.5) {
            array[arraySize] = "t";
            numOfTails++;
         } else {
            for (int j = 0; j <= arraySize; j++) {
               if (randomNumber >= 0.5) {
                  array[arraySize] = "h";
                  numOfHeads++;
               }
            }

         }
      }
   }
}

and the tester class:

import java.util.Scanner;
public class CointTossTester {
   public static void main (String[] args){
      Scanner sc = new Scanner(System.in);

      System.out.println("Number of tosses ");
      int number = sc.nextInt();

      CoinToss coin = new CoinToss(number);

      coin.tossCoin();
      System.out.println("Ight deez niggers be: " +coin.array);
}
}

Thanks!

Philip
  • 13
  • 1
  • You are always accessing the array at 1 past the last index in the tossCoin method. You probably want to use your loop counter variables instead of using the full length as the index. It also looks like you also created your array with size 0. – takendarkk Nov 08 '17 at 21:32
  • 1
    You should only initialise `array` once you have a value for `arraySize`. Also, `array[arraySize]` => `array[i]`. – AntonH Nov 08 '17 at 21:34
  • Plus, the comparator for the upper limit of the loops should be `<` (not `<=`) in both loops. – kalabalik Nov 08 '17 at 21:36
  • I tried that too, using i and j instead, but that results in this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at CoinToss.tossCoin(CoinToss.java:38) at CointTossTester.main(CointTossTester.java:11) – Philip Nov 08 '17 at 21:36
  • the problem is here `array[arraySize]`. `arraySize = last intex + 1`, because is java indexing start from zero. – dehasi Nov 08 '17 at 21:38
  • That is because you have multiple problems. You created an array with 0 length, then used the length as the index for accessing the array which will always be out of bounds, and even if all of that was fixed your loops go one iteration too many because of your comparison having an equal sign. There may be more but I'm looking at this on my phone and it's a bit hard to read. – takendarkk Nov 08 '17 at 21:38

3 Answers3

1

public void tossCoin() { for (int i = 0; i <= arraySize; i++) { double randomNumber = Math.random();

You did not instantiate arraySize properly.

Edit (thanks for the comment below):

First things first: When you're declaring properties for your CoinToss class, your arraysize is defaulted to 0, but then in next two lines you are declaring String [] array = new String[arraySize]. This means your array is declared as an array of size 0.

To fix THAT particular issue you have to split public String [] array = new String[arraySize] into public String [] array; in your class field declaration and array = new String[arraySize] in constructor. So it looks like that:

public class CoinToss {

    public int heads;
    public int tails;
    public int totalToss;
    public int arraySize;
    public int numOfTails = 0;
    public int numOfHeads = 0;
    public String[] array;

    public CoinToss(int NumberOfTosses) {
        arraySize = NumberOfTosses;
        array = new String[arraySize];
    }

    // rest of the code
}

This fixes one problem.

Second one is that that further down in the code of tossCoin method you have:

    public void tossCoin() {
        for (int i = 0; i <= arraySize; i++) {
            double randomNumber = Math.random();

            if (randomNumber < 0.5) {
                array[arraySize] = "t";
                numOfTails++;
            } else {
                for (int j = 0; j <= arraySize; j++) {
                    if (randomNumber >= 0.5) {
                        array[arraySize] = "h";
                        numOfHeads++;
                    }
                }

            }
        }
    }

And lines: for (int i = 0; i <= arraySize; i++) { and for (int j = 0; j <= arraySize; j++) { are wrong because at some point you are accesing 5th element of the array, when its last index is 4.

Bobzone
  • 276
  • 2
  • 12
1

The main issue is that you are not using the correct variable to put the "h" or "t" value in the array. You use:

array[arraySize] ...

However, arraySize is the size of the array. You need to use the variable i, which is the loop counter:

array[i] = "t"; // or "h", depending.

You're also not doing the correct number of loops:

for (int i = 0; i <= arraySize; i++) {

Since you have indicated <=, it means that you go up to the size of the array. But since array indices start at 0, you should instead be using:

for (int i = 0; i < arraySize; i++) { // notice "<" instead of "<="

I would also recommend only initialising your String array once you have your value for arraySize, in the Constructor:

public CoinToss(int NumberOfTosses) {
    arraySize = NumberOfTosses;
    array = new String[arraySize];
}
AntonH
  • 6,359
  • 2
  • 30
  • 40
1

Change your initialization of array to declaration like all the others:

public String [] array;

Then, change your constructor so it initializes the array correctly:

public CoinToss(int NumberOfTosses) {
   arraySize = NumberOfTosses;
   array = new String[arraySize];
}

Your for loop is going from 0 to arraySize (which is one more than the last index, so it won't work). It should instead go to arraySize-1, which would change it to:

for (int i = 0; i < arraySize; i++) {

Also, you shouldn't use arraySize to access array, but i, which is your loop variable, like this:

array[i] = "t";

Now, you don't need another cycle, nor the second conditional, the random number is either lower than 0.5 or higher, and you can put it accordingly, like this:

if (randomNumber < 0.5) {
   array[i] = "t";
   numOfTails++;
} else {
   array[i] = "h";
   numOfHeads++;
}

Finally, printing an array isn't as simple as just joining it with a string, you should either go through it or print it using another utility (I personally like Arrays.toString method) like this:

System.out.println("Ight deez niggers be: " +Arrays.toString(coin.array));

Here you have a working example [Note: I put the main method on the Coin class]

Piyin
  • 1,823
  • 1
  • 16
  • 23