Java:为随机生成并放置在数组中的整数创建频率表

gwbalxhn  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(113)

谢谢大家!我尽我所能清理了代码,并决定将完成的代码与示例输出一起粘贴,供其他学生查看,如果他们选择使用部分代码。

public class Arrays {
  public static void main(String args[]) {
    //Assigning the array length according to the user's input
    int N = Integer.parseInt(args[0]);
    int randoms[] = new int[N];
    //Filling the array with random integer values
    System.out.println("The numbers generated are: ");
    for (int i=0; i<randoms.length; i++) {
      randoms[i] = (int) (Math.random()*10 + 1);
      System.out.print(randoms[i] + " ");
    }
    double sum = 0.0;
    for (int i=0; i<randoms.length; i++) {
      sum += randoms[i];
    }
    System.out.println("\nThe average of the values is " + (sum/N));
    int freq[] = new int[11];
    for (int i=0; i<randoms.length; i++){
      freq[randoms[i]] += 1; 
    } 
    System.out.println("Number\tFreq");
    for (int i=1; i<freq.length; i++){
      System.out.println(i + "\t" + freq[i]);
    }
  }
}

样本输出:

> java Arrays 15
The numbers generated are: 
4 8 1 10 6 7 8 4 6 6 3 4 4 5 8 
The average of the values is 5.6
Number  Freq
1       1
2       0
3       1
4       4
5       1
6       3
7       1
8       3
9       0
10      1
enyaitl3

enyaitl31#

正如阿德里安指出的,你目前只计算1。我会有点棘手,而不是做一个检查,对每一个,简单地使用随机整数,以选择正确的元素递增

for (int i=0; i<randoms.length; i++){
    freq[randoms[i]-1] += 1; 
 }
lxkprmvk

lxkprmvk2#

谢谢你的帮助!在查看代码足够长的时间后,我意识到在我的输出中我使用了

for (int i=0; i<randoms.length; i++){
      System.out.println(randoms[i] + " appeared " + freq[i] + " times");

我本该用

for (int i=0; i<randoms.length; i++){
      System.out.println(randoms[i] + " appeared " + freq[randoms[i]] + " times");

相关问题