当前位置: 代码迷 >> java >> 名为randTest的静态void方法,它使用单个整数参数n
  详细解决方案

名为randTest的静态void方法,它使用单个整数参数n

热度:55   发布时间:2023-07-16 17:52:37.0

我在弄清楚这段代码时遇到了麻烦,在randTest方法中,我必须声明一个名为counts的10个元素的int数组。 这将用于记录randInt返回每个可能值的频率,randInt是我创建的静态int方法,该方法生成一个随机整数。

我必须调用randInt n次,每次递增与返回值相对应的count元素的计数。

这是我到目前为止为randTest方法生成的代码:

    public static void randTest(int n){

    int [] counts = new int [10];

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

这是你想要的?

我猜想,您已经将randTest()的结果限制为从0到9的整数。为确保没有问题,我添加了IllegalArgumentException。

public static void randTest(int n) throws IllegalArgumentException {
    if ((n < 0 ) || (n > 9)) {
        throw new IllegalArgumentException("Only values between 0 and 9 are accepted.");
    }

    int [] counts = new int [10];

    for(int i=0; i<n; i++) {
        int rInt = RandInt();
        counts[rInt]++;
        System.out.println("Integer of value " + rInt + " was called " 
                            + counts[rInt] + " times so far.");
    } 
}
  相关解决方案