输入一串数字,统计其中每一个数字的个数
令数组的下指代所输入的数字,下标所对应的数为该数字的个数
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int[] a = new int[10];
//无需对数组进行初始化,java在创建数组的过程就全部初始化为零
while (x != -1){//输入-1是输入结束
if(x <= 9 || x >= 0){
a[x]++;
}
x = input.nextInt();
}
for(int i = 0;i < a.length;i++){
System.out.print(i+"有"+a[i]+"个 ");
}
}
结果
1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 7 5 1 2 3 0
-1
0有1个 1有2个 2有2个 3有2个 4有2个 5有3个 6有2个 7有3个 8有2个 9有2个
Process finished with exit code 0