我已经完成这项任务两天了,我遇到了这样的困难!我的任务要求我创建一个程序:
- 询问用户想要执行多少次运行(例如 20 次翻转 3 次)(输出应该有每次试验之间的比较)
- 询问用户他希望他的硬币翻转多少次(他最多可以翻转 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.");
提前致谢!