计算数组中显示的整数数量

时间:2016-06-22 09:20:52

标签: java arrays count element

我有一个100个随机元素数组,每个元素的范围是0-10,我需要计算每个整数输入的次数(例如1,2,2,3,8,8,4。 ..)

输出:

1 - 1

2 - 2

3 - 1

8 - 2

4 - 1

到目前为止我的代码是:

import java.util.Random;

public class Asses1 {
    public static void main(String[] args) {

        getNumbers();
      }

    private static int randInt() {
        int max = 10;
        int min = 0;

        Random rand = new Random();

        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static int[] getNumbers() {
        int number = 100;
        int[] array = new int[number];
        for (int i = 0; i < array.length; i++) {
            System.out.println(randInt());
        }

        System.out.println(number+" random numbers were displayed");
        return array;
    }

}

4 个答案:

答案 0 :(得分:1)

int[] array2 = new int[11];

for (int i = 0; i < array.length; i++){
    array2[randInt()]++
}
for (int i = 0; i < array.length; i++)
    System.out.println(String.valueOf(i) + " - " + String.valueOf(array2[i]));

我所做的是:

  1. 创建一个帮助数组 array2 ,用于存储每个数字的出现次数。
  2. 生成数字时增加帮助数组的出现次数。

答案 1 :(得分:1)

添加此方法,将进行计数:

public static void count(int[] x) {
    int[] c=new int[11];

    for(int i=0; i<x.length; i++)
        c[x[i]]++;

    for(int i=0; i<c.length; i++)
        System.out.println(i+" - "+c[i]);
}

并将main更改为this,以便调用上一个方法:

public static void main(String[] args) {

    count(getNumbers());
  }

另外,将for中的getNumbers循环更改为此内容,以便使用生成的数字填充array,而不仅仅是打印它们:

    for (int i = 0; i < array.length; i++) {
        array[i] = randInt();
        System.out.println(array[i]);
    }

答案 2 :(得分:1)

以下是如何在java 8中完成的

// Retrieve the random generated numbers
int[] numbers = getNumbers();
// Create an array of counters of size 11 as your values go from 0 to 10
// which means 11 different possible values.
int[] counters = new int[11];
// Iterate over the generated numbers and for each number increment 
// the counter that matches with the number
Arrays.stream(numbers).forEach(value -> counters[value]++);
// Print the content of my array of counters
System.out.println(Arrays.toString(counters));

<强>输出:

[12, 11, 7, 6, 9, 12, 8, 8, 10, 9, 8]

NB:您的方法getNumbers不正确您应该将其修复为下一个:

public static int[] getNumbers() {
    int number = 100;
    int[] array = new int[number];
    for (int i = 0; i < array.length; i++) {
        array[i] = randInt();
    }

    System.out.println(number+" random numbers were displayed");
    return array;
}

答案 3 :(得分:-1)

Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        int temp;
        for (int i = 0; i < array.length; i++) {
            temp=randInt();
            if(map.containsKey(temp)){
                map.put(temp, map.get(temp)+1);
            }else{
                map.put(temp, 1);
            }
        }