建立一个大小为10的int数组,例如随机出现的数字为5则将下标为5的数字加1.
/*
The random digits:
--------------------------------
2 5 9 9 1 9 2 7 0 1
9 2 4 2 7 5 4 5 6 1
2 4 7 8 1 7 6 8 2 9
5 5 9 9 2 5 2 2 5 6
6 9 2 2 1 9 6 2 1 3
2 3 5 0 6 4 1 2 1 7
8 3 5 2 8 9 5 9 8 9
8 8 8 0 0 3 0 2 5 8
3 3 7 8 2 3 6 3 9 4
4 6 5 9 8 5 2 2 6 6
0 ~ 9 ocurr times:
--------------------------------
0 occur times:5
1 occur times:8
2 occur times:19
3 occur times:8
4 occur times:6
5 occur times:13
6 occur times:10
7 occur times:6
8 occur times:11
9 occur times:14
*/
public class CountDigitOccur {
public static void main(String[] args) {
final int SIZE = 10;
final int MAX_SIZE = 100;
int[] counts = new int[SIZE];
System.out.println("The random digits:");
System.out.println("--------------------------------");
for (int i = 0; i < MAX_SIZE; i++) {
int digits = (int)(Math.random() * 10);
System.out.print(digits + " ");
if ((i + 1) % 10 == 0)
System.out.println();
counts[digits]++;
}
System.out.println("\n0 ~ 9 ocurr times:");
System.out.println("--------------------------------");
showCounts(counts);
}
public static void showCounts(int[] pr) {
for (int i = 0; i < pr.length; i++)
System.out.println(i + " occur times:" + pr[i]);
}
}