Sunday, 25 August 2013

ArrayIndexOutOfBoundsException, Arrays, and Counting Occurrences of Integers

ArrayIndexOutOfBoundsException, Arrays, and Counting Occurrences of Integers

I've been on this assignment for two days now and I'm having such a
difficult time! My assignment asks me to create a program that:
asks how many times the user would like to perform the run (e.g. 3 flips
of 20) (the output should have a comparison between each trial)
asks the user how many times he would like his coin to flip (he can flip
up to 1000 times)
randomly generates a number between 1 and ten, store all the numbers in an
array
It must also show how many times each number out of 10 showed up, what
number showed up the most, and if even numbers are heads, and odd numbers
are tails, what side of the coin came up the most. Please help me, I've
tried writing the code but I'm having such a hard time and I'm really
stressed on time!
Here's my code:
import java.io.*;
import java.util.Random;
public class ColCoin
{
public static void main(String[] args) throws IOException
{
//set variables
String timesString;
String run;
int times;
int runNum;
int i = 0;
int x;
//input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//random object
Random r = new Random();
System.out.print("How many times would you like to perform a run
through the flips? ");
run = br.readLine();
runNum = Integer.parseInt(run);
do
{
//ask how many times the coin will flip
System.out.print("Please input the amount of times you would like
to flip the coin (1-1000): ");
timesString = br.readLine();
//convert String into an integer
times = Integer.parseInt(timesString);
if((times > 1000)||(times < 1))
{
System.out.println("ERROR! Must input an integer between 1 and
1000!");
}
System.out.println("You chose to flip the coin " + times + "
times.");
} while((times > 1000)||(times < 1));
for(x=0; x <= runNum; x++)
{
//create array
int flip[] = new int[times];
int countArray[] = new int[i];
//create a new variable
int storeTime;
for(storeTime = 0; storeTime < flip.length; storeTime++)
{
flip[storeTime] = r.nextInt(10) + 1;
// the line above stores a random integer between 1 and 10
within the current index
System.out.println("Flip number " + (storeTime+1) + " = " +
flip[storeTime]);
}
//display the counts
for(i=0; i < 10; i++)
{
System.out.println("The occurences of each of the numbers is: ");
System.out.println((i+1) + " appears " + countArray[i] +
"times.");
}
}
}
}
It also gave an ArrayIndexOutOfBoundsException error on line 64 and I'm
not sure why:
System.out.println((i+1) + " appears " + countArray[i] + "times.");
Thanks in advance!

No comments:

Post a Comment