Java randTest()方法,该方法将单个int n作为参数
下面是我必须遵循的代码说明,我已经完成了大部分代码,但我似乎缺少使其正确编译的元素 一个名为randTest的静态void方法,它接受一个整数参数n。这应执行以下操作: 声明一个名为counts的包含10个元素的整数数组。这将用于记录randInt返回每个可能值的频率 调用randInt n次,每次递增与返回值对应的counts元素的计数Java randTest()方法,该方法将单个int n作为参数,java,random,count,int,increment,Java,Random,Count,Int,Increment,下面是我必须遵循的代码说明,我已经完成了大部分代码,但我似乎缺少使其正确编译的元素 一个名为randTest的静态void方法,它接受一个整数参数n。这应执行以下操作: 声明一个名为counts的包含10个元素的整数数组。这将用于记录randInt返回每个可能值的频率 调用randInt n次,每次递增与返回值对应的counts元素的计数 public static void randTest(int n){ int [] counts = new int [10]; int sampleSiz
public static void randTest(int n){
int [] counts = new int [10];
int sampleSize = 10000;
//int n = sampleSize;
int RandNum = RandInt();
System.out.println ("Sample Size: " + sampleSize);
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
for(int i=0;i<10000;i++){
counts[ RandNum ] = counts[ RandNum ] + 1;
counts[i] = RandInt();
System.out.println(counts[n]);
}
}
然后必须将信息打印到结果表中,如下所示:
编译时会出现什么错误 首先,您的计数大小只有10,所以您无法进行计数[i],因为我最多可以达到10000 您注释掉了int n,因此无法使用System.out.printlncounts[n]
int RandNum=RandInt;,您必须限制或更改此值,因为计数的大小仅为10。您正确地增加了计数,但为什么要在之后更改计数[i]的值?您还需要每次通过for循环获得一个新的随机数:
for(int i=0;i<10000;i++){
int randomNum = rand.nextInt(10);
counts[ randomNum ] = counts[ randomNum ] + 1;
}
}
我相信这个问题是因为 你有counts[i]=RandInt;这就是破坏一切,因为我可以大于数组的大小。
另外,您从未更改过随机数的值。您有什么问题?您的问题到底是什么?您的代码中有很多问题:不尊重CamelCase,字符串数组的命名不好,生成的随机数的数量,它们的计数方式等
public static void randTest(int n){
int [] counts = new int [10];
String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
System.out.println(Arrays.toString(intArray));
for(int i=0;i<10000;i++){
int randomNumber = RandInt();
counts[ randomNumber ] = counts[ randomNumber ] + 1;
System.out.println("Added one to value : " + randomNumber);
}
}