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

时间:2015-03-02 02:58:57

标签: java arrays integer frequency

谢谢大家!我尽我所知清理了代码,并决定将完成的代码和示例输出粘贴到其他学生身上,以及他们是否选择使用部分代码。

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

2 个答案:

答案 0 :(得分:0)

正如阿德里安指出的那样,你目前只计算一些。我会有点棘手而不是检查每一个,只需使用随机整数来选择正确的增量元素

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

答案 1 :(得分:0)

感谢您的帮助!在看了足够长的代码后,我意识到在我的输出中我正在使用

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