ArrayIndexOutOfBoundsException,Arrays和Counting End of Integers

时间:2013-08-25 11:42:31

标签: java arrays

我现在已经做了两天这个任务了,我有这么艰难的时间! 我的任务要求我创建一个程序:

  • 询问用户想要执行运行的次数(例如3 翻转20)(输出应该在每个试验之间进行比较)
  • 询问用户他希望他的硬币翻转多少次(他可以 翻转1000次)
  • 随机生成1到10之间的数字, 将所有数字存储在数组中

它还必须显示10个中的每个数字出现的次数,最多显示的数字,如果偶数是头部,奇数是尾部,则硬币的哪一侧出现最多。 请帮助我,我已经尝试过编写代码,但是我很难过,而且我真的很紧张!

这是我的代码:

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.");
        }
    }
}
}

它还在第64行给出了一个ArrayIndexOutOfBoundsException错误,我不确定原因:

System.out.println((i+1) + " appears " + countArray[i] + "times.");

提前致谢!

3 个答案:

答案 0 :(得分:2)

问题在于:

int countArray[] = new int[i];

使用此代码,您可以创建一个包含i个元素的数组,索引范围为0到i-1。但在你的情况下int仍然是0.所以数组的维度为零(似乎你从来没有使用该数组输入东西)

System.out.println((i+1) + " appears " + countArray[i] + "times.");

在这里你要求数组给你元素i!= 0,但显然你不能,因为数组的大小为零。

答案 1 :(得分:1)

问题在于此部分

  

int countArray [] = new int [i];

在创建这个数组时,我是零,因此实际上,数组永远不会被填充,所以,它总是空的。

答案 2 :(得分:0)

您在数组中使用动态长度,但是您创建的循环用于显示您使用固定长度的输出(下面的行)。

for(i=0; i < 10; i++)