1. 程式人生 > >從鍵盤輸入10個0-9的整數,統計為1、2、3的數字和其他數字的個數

從鍵盤輸入10個0-9的整數,統計為1、2、3的數字和其他數字的個數

從鍵盤輸入10個整數,合法值為1、2、3,不是這三個數剛為非法數字。試程式設計統計每個整數和其他數字的個數。

import java.util.Scanner;
public class Tt{
public static void main(String[] args){
int[] num = new int[10];
int n, n1, n2, n3; //計數
n = n1 = n2 = n3 = 0;
System.out.println("請輸入10個0-9的整數:");
Scanner input = new Scanner(System.in);
for(int i=0; i<num.length; i++){
num[i] = input.nextInt();
switch(num[i]){
case 1: n1++;
break;
case 2: n2++;
break;
case 3: n3++;
break;
default: n++;
break;
}
}
System.out.printf("數字1的個數:%d\n數字2的個數:%d\n數字3的個數:%d\n其它數字的個數:%d\n", n1, n2, n3, n);
}
}
/*--------------------------
請輸入10個0-9的整數:
2
5
3
3
1
6
4
1
3
3
數字1的個數:2
數字2的個數:1
數字3的個數:4
其它數字的個數:3
--------------------------*/