標準入力からの入力に現れた数字をカウントする (ver.2)

明解C言語 入門編 > 8. いろいろなプログラムを作ってみよう >

標準入力からの入力に現れた数字をカウントする (ver.2)

Java
import java.util.Scanner;

class Lesson066 {
    public static void main(String[] args) {
        int[] cnt = new int[10];

        Scanner stdIn = new Scanner(System.in);

        String str;
        while (stdIn.hasNext()) {
            str = stdIn.next();

            for (int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if (('0' <= ch) && (ch <= '9'))
                    cnt[ch - '0']++;
            }
        }

        for (int i = 0; i < 10; i++)
            System.out.printf("'%d' : %d\n", i, cnt[i]);
    }
}

実行結果

L:\>java Lesson066
3.14159265
^Z
'0' : 0
'1' : 2
'2' : 1
'3' : 1
'4' : 1
'5' : 2
'6' : 1
'7' : 0
'8' : 0
'9' : 1