2012-12-16 27 views
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

回答

6

它看起來像,而不是

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

你應該做

t[temp]++; 
+0

你說得對,我真的不知道爲什麼我把它放在首位。非常感謝! – Jean

0

或者你可以寫。

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

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

    return count; 
}