java - 测试随机数生成器

标签 java arrays sorting int

我在打印表格中结果的前两列时遇到问题,但由于我是编程新手,我遇到了问题,想知道问题出在我的代码中。我必须创建的简要说明:

  • 无参数静态 int 方法 randInt(),它将返回 0..9 范围内的随机整数(含)。此方法将包含对 Math.random() 的调用。

  • 名为 randTest 的静态 void 方法,它采用单个整数参数 n。这应该执行以下操作:

  • 声明一个包含 10 个元素的 int 数组,名为 counts。这将用于记录 randInt 返回每个可能值的频率。

  • 调用 randInt n 次,每次递增与返回值对应的 counts 元素的计数。

  • 以清晰的表格形式将结果打印到控制台。输出应如下所示:

enter image description here

这是我的代码:

import java.util.Arrays;

public class RandNumGenerator {

    public static int RandInt(){
        double n = Math.random()*10;
        return (int) n;
        }

    public static void randTest(int n){
        int [] counts = new int [10];

        for(int i=0;i<n;i++){
            counts[i] = RandInt();
            System.out.println(counts[i]);
            } 
        }

    public static void main(String[] args) {
        int sampleSize = 1000;      
        System.out.println ("Sample Size: " + sampleSize);
        String[] intArray = new String[] {"Value","Count","Expected","Abs Diff","Percent Diff"};
        System.out.println(Arrays.toString(intArray));
        randTest(10);
        }
    }

最佳答案

public static void randTest(int n){

请你思考的问题:这里的参数是什么?提示:这不是 10...您实际上想要做 n 次什么?

counts[i] = RandInt();

您确实想创建 10 个随机数并将它们存储到数组中吗?没有。您想要创建“sampleSize”数字并在正确的位置增加数组。正确的位置是什么?

计数[正确位置] = 计数[正确位置] + 1;

...如果你能找出正确的位置,那就更正确了。

此外,我会将输出从 main 方法移至 randTest() ,在那里你可以将所有内容放在一起。

关于java - 测试随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31656060/

相关文章:

php - 如何在 php 中访问 protected json 数组

javascript - 根据键是否存在和值对对象数组进行排序

python - 按多个元素按升序和降序对元组列表进行排序

javascript - Chrome Array.sorting 数字乱序

r - 从距离矩阵开始查找 K 个最近邻

java - 关闭 JDialog 时没有 WindowEvent

java - 是否可以通过 Spring Security 以编程方式进行身份验证并使其持久化?

java - 在安装了 eclipse juno 和 java 8 的情况下加载 maven Artifact 时出错

java - 从线程创建 Intent

javascript - 使用 async/await 和 then() 如何将结果保存在数组中