我需要使用数组编写一个程序,它接受一个数字并返回该数字中每个数字的事件数。我想我可能把这里的事情复杂化了。
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 的个数,而且无论如何都是错误的。有人能把我推向正确的方向吗?
最佳答案
声明包含十个元素的数组 ([0..9]) - 数字中的每个数字都会出现在其中。只需使用 counts[3]
即可得到数字 3
的出现次数。
然后您只需遍历字符串编号并将下一个字符读取为整数并增加计数器。这样你只有一个循环。例如,如果您的数字中有 3
,则您使用 counts[3]++
。
关于java - 使用数组计算数字中每个数字的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34266863/