gpt4 book ai didi

java - 计算随机生成的数字中出现的次数

转载 作者:行者123 更新时间:2023-12-01 23:50:03 26 4
gpt4 key购买 nike

我有一个 Java 程序,可以生成 100 个 0 到 9 之间的随机整数,我需要让它显示每个数字的计数。例子是这样的:

*************************************************************************
Generating 100 random integers between 0 and 9
Number 1 = 3
Number 2 = 0
… (your program must display all generated numbers)
Number 100 = 8
*************************************************************************
0 occurs 1 time
1 occurs 9 times
2 occurs 18 times
3 occurs 20 times
4 occurs 5 times
5 occurs 20 times
6 occurs 1 time
7 occurs 1 time
8 occurs 25 times
9 occurs 0 time
*************************************************************************

到目前为止我有这么多:

 import java.util.Random;
public class World {
public static void main(String[] args) {

public void generateNumber(){
System.out.println("*************************************************************************");
System.out.println("Generating 100 random integers between 0 and 9");

Random aGenerator = new Random();

int randomArray[]=new int[101];
int countArray[]=new int[10];

//generate the numbers and store into an array
int j;
for(int i=1; i<101; ++i) {
j=i;
randomArray[i]=aGenerator.nextInt(10);

//displaying numbers
System.out.println("Number " + j + " = " + randomArray[i]);

}



System.out.println("*************************************************************************");

//counting the numbers
for(int i=1;i<100;i++){
countArray[randomArray[i]-1] = countArray[randomArray[i]-1]+1;

//displaying the counts
j=i;
System.out.println(randomArray[i]+" occurs "+countArray[i]+ " times");

}




}
}
}

并且生成和显示随机数工作正常,但是,计数部分如下所示

*************************************************************************
5 occurs 0 times
7 occurs 0 times
7 occurs 0 times
9 occurs 1 times
2 occurs 0 times
2 occurs 2 times
1 occurs 0 times
4 occurs 1 times
at Generator.generateNumber(2 appears 0 times
Generator.java:33)
at World.main(World.java:17)

请帮我看看我哪里做错了?非常感谢您抽出时间!

最佳答案

您的代码比需要的更复杂。只需使用:

//to store the counts
for (int r : randomArray)
countArray[r]++;

//to access the counts
for (int x = 0; x < countArray.length; x++) {
System.out.println("" + x + " occurs " + countArray[x] + " times");
}

关于java - 计算随机生成的数字中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16429565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com