0

特定の数字に各数字が何回出現するかをカウントするモジュールを作成しようとしています。私が抱えている問題は、対応する数字の配列値に 1 を追加する代わりに、10 を追加するように見えるか、または配列のデフォルト値 (この場合は 0 ) を連結することです。

私のモジュール:

public class UtilNumber{
    public static int [] Occurence(int nb){
        int temp;
        int [] t = new int [10];

        while (nb !=0){
            temp = nb % 10;
            for (int i = 0; i < t.length ; i++){
                t[temp]++;
            }
            nb /= 10;
        }
        return t;
    }
}

私のメイン:

import java.util.scanner;

public class Primary{
    public static void main(String [] args){
        Scanner keyboard = new Scanner(System.in);
        int [] tab;
        int nb = keyboard.nextInt();
        tab = UtilNumber.Occurence(nb);
        for (int i = 0 ; i < tab.length ; i++){
            if (tab[i] != 0){
                System.out.println(i+" is present "+tab[i]+" time(s).");
            }
        }
    }
}

たとえば、888 と入力すると 3 が返されるはずですが、代わりに 30 が返されます。

4

2 に答える 2

6

代わりに

 for (int i = 0; i < t.length ; i++){
   t[temp]++;
 }

あなたはただやるべきです

 t[temp]++;
于 2012-12-16T17:34:42.313 に答える
0

または、書くことができます。

public static int [] occurence(long nb){
    int[] count = new int [10];

    for(;nb > 0;nb /= 10) 
        count[nb % 10]++;

    return count;
}
于 2012-12-16T18:12:46.677 に答える