我需要使用數組編寫一個程序,該數組需要一個數字並返回該數字中每個數字的事件數。我想我可能在這裏過分複雜。使用數組計算每個數字的位數
import java.util.*;
class Exercice7 {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Veuillez saisir un nombre naturel:"); // Get number
int n = sc.nextInt(); // Store number as n
String str = Integer.toString(n); // Store n as string
int length = str.length(); // Store string length as length
int arr[] = new int[length]; // Declare array with as many elements as n has digits
int digit[] = {0,1,2,3,4,5,6,7,8,9}; // Declare array with the digits to look for
int count = 0; // Number of occurences of each digit
for (int i=(length-1); i>=0; i--) { // Fill array with digits from number input
while (n>0) {
arr[i]= n%10;
n = n/10;
}
}
for (int j=0; j<10; j++) {
count = 0;
for (int i=0; i<length; i++) {
if (arr[i]==digit[j]) {
count++;
}
}
if (count>0) {
System.out.println(digit[j] + " occurs " + count + " times.");
}
}
}
}
此代碼只返回0和1的數量,而且它是錯誤的。有人能把我推向正確的方向嗎?
不知道這是你的意思,但它似乎工作! – ktouchie
嗯,我很高興你已經使它的工作 - 這就是爲什麼我沒有提供任何代碼。當你爲(困難的)問題做出自己的回答時,它會更好,更有趣。幹得好,男人,即使我的方式有點不同:) – deem
謝謝,相信!我完全同意。 :) – ktouchie