繁体   English   中英

ArrayIndexOutOfBoundsException,数组和整数的计数

[英]ArrayIndexOutOfBoundsException, Arrays, and Counting Occurrences of Integers

我从事这项工作已有两天了,我现在很困难! 我的作业要求我创建一个程序,该程序:

  • 询问用户要执行多少次跑步(例如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.");

提前致谢!

问题在这里:

int countArray[] = new int[i];

使用此代码,您将创建一个包含i个元素的数组,索引从0到i-1。 但是在您的情况下,int仍然为0。因此数组的维数为零(而且似乎您从未使用该数组输入内容)

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

在这里,您要求数组给元素i!= 0,但是显然您不能,因为数组的尺寸为零。

问题在这部分

int countArray [] = new int [i];

创建此数组时,i为零,因此实际上该数组从未填充,因此它始终为空。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM