我做这个任务已经有两天了,我现在过得很艰难!我的任务要求我创建一个程序:
它还必须显示每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.");提前感谢!
发布于 2013-08-25 11:50:56
问题在于:
int countArray[] = new int[i];使用这段代码,您可以创建一个包含i元素的数组,索引从0到i-1。但在你的例子中int仍然是0。因此,数组的维数为零(而且,似乎从未使用该数组输入某些内容)。
System.out.println((i+1) + " appears " + countArray[i] + "times.");在这里,您要求数组给出元素i!=0,但显然不能,因为数组的维度为零。
发布于 2013-08-25 13:11:43
问题就在这部分。
int countArray[] =新inti;
在创建这个数组时,我是零,因此,这个数组从来没有被填充过,所以它总是空的。
发布于 2013-08-25 12:24:31
您在数组中使用的是动态长度,但是您创建的用于显示使用固定长度(下面的行)的输出的循环。
for(i=0; i < 10; i++)
https://stackoverflow.com/questions/18428603
复制相似问题