我有一个由0到10之间的数字组成的数组。例如,
1, 3, 5, 7, 5, 3, 1, 9
我想计算数组中每个数字从0到10的出现次数。像这样的东西(模拟输出):
number | occurrence
0 0
1 2
2 0
3 2
4 0
5 2
6 0
7 2
8 0
9 1
10 0
编辑:这是一项高中作业:编写一个程序,反复提示用户在测试中提供分数(满分10分)。程序应继续询问用户标记,直到提供负值。应忽略任何大于10的值。一旦程序读完所有分数,就应该生成一个包含以下标题的表格(并自动填写表格的其余部分): 分数#出现次数 然后程序应计算平均分数,四舍五入到小数点后一位。 我的代码回答了这个问题:
public static int[] resize(int[] a) {
int[] expandedArray = new int[a.length + 1];
for (int i = 0; i < a.length; i++) {
expandedArray[i] = a[i];
}
return expandedArray;
}
public static void main (String[]args) {
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
boolean positive = true;
int count = 0;
int[] originArray = new int[0];
for (@SuppressWarnings("unused")
int i = 0; positive; i++) {
System.out.println("Enter a score: ");
int input = scan.nextInt();
System.out.println("The input is recorded: " + input);
if (input < 0) {
positive = false;
System.out.println("The input is negative.");
}else if (input > 10){
System.out.println("///INVALID///: Must be out of 10!");
} else {
System.out.println("count: " + count);
originArray = resize(originArray);
System.out.println("originArray resized");
originArray[count] = input;
System.out.println("The index = count = " + count +" would be assigned input: " + input);
for (int j = 0; j <= count; j++) {
System.out.println(j + ": " + originArray[j]);
}
count++;
System.out.println("count++: " + count);
}
}
System.out.println("Program has stopped taking inputs. Outputting results:");
System.out.println(" Score | Occurrences ");
}
答案 0 :(得分:0)
如果给出输入数组,则以下代码将在counts数组中为您生成结果。
int [] counts = new int[11];
for (int i = 0; i < input.length; i++) {
counts[input[i]]++;
}