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!