【问题标题】:randTest () method that takes a single int n as an argumentrandTest () 方法,将单个 int n 作为参数
【发布时间】:2015-07-27 19:28:55
【问题描述】:

以下是我必须遵循的代码说明,我已经完成了大部分代码,但我似乎缺少使其正确编译的元素。

一个名为 randTest 的静态 void 方法,它接受一个整数参数 n。这应该执行以下操作:

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

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

    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]);
        } 
    }
    

然后必须将信息打印到结果表中,如下所示:

【问题讨论】:

  • 你有什么问题?
  • 你的问题到底是什么?
  • 您的代码中存在许多问题:不尊重 CamelCase、命名不佳(intArray 用于字符串数组)、生成的随机数的数量、它们的计数方式等

标签: java random count int increment


【解决方案1】:

您在编译时究竟遇到了什么错误?

首先,您的 counts 大小只有 10,因此您不能使用 counts[i],因为 i 可能高达 10,000。

你注释掉了int n,所以你不能System.out.println(counts[n]);

int RandNum = RandInt();,您必须限制或更改它,因为counts 的大小仅为 10。

【讨论】:

    【解决方案2】:

    你在增加计数是对的,但是为什么你改变 counts[i] 之后的值?你还需要每次通过for循环获取一个新的随机数:

    for(int i=0;i<10000;i++){
        int randomNum = rand.nextInt(10);
        counts[ randomNum ] = counts[ randomNum ] + 1;
        } 
    }
    

    【讨论】:

      【解决方案3】:

      我相信问题来自for

      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);
        } 
      }
      

      你有 counts[i] = RandInt(); 打破一切,因为 i 可以大于数组的大小。 另外,您永远不会更改随机数的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        相关资源
        最近更新 更多