我的一项任务遇到问题。 我被要求构建一个用户将输入长度的数组。 最后,主要目标是打印任何数字中出现频率最高的数字。 例如,如果数组的长度为 4,数字为:1000, 212, 1345, 88818 - 应打印的数字是 88818,因为它有更多相似的数字(数字 8 出现了 4 次)。
我确信到目前为止我所拥有的都很好,但我发现该程序不完整,原因有两个:
- 如果数组的大小大于 2,则创建数组后不会发生任何事情。
- 如果其中一个数字的位数超过一位,则不会发生任何情况。
我已经尝试找出问题所在 5 个小时了,但仍然没有成功。 如果有人能帮助我,我将非常感激。
只是指出,我不允许使用不是 int[] 类型的数组,以及任何比数组更高级的 Material 。
这是我到目前为止所拥有的:
public static void frequentNumber() {
int num=0;
while (true) {
System.out.println("Enter array size");
num = in.nextInt();
if (num >=1)
break;
}
int[] a = createArray(num);
int[] freq = new int[a.length]; //holds the frequency of each number in the primary array
int count = 0, b;
for (int i=0; i<a.length; i++) {
b=a[i];
while (b > 0) { // counts the number of digits
count++;
b/=10; }
int[] k = new int[count]; // array of digits
b=a[i];
for (int j=0; j<k.length; j++) { // enters each digit into it's own box at the digits array
k[j] = b % 10;
b /= 10; }
int[] sortedK = new int[k.length];
sortedK = sortArray(k); // sorts the array with bubble sort
int max=0, maxNew=0;
for (int s=1; s < sortedK.length; s++) {
if (sortedK.length == 1) {
maxNew++;
break; }
else if (sortedK[s] != sortedK[s-1])
max=0;
while (sortedK[s] == sortedK[s-1]) {
max++;
if (max > maxNew)
maxNew=max;
}
}
freq[i] = maxNew; /* at this point, maxNew will have the amount of max frequent digits
for the number at a[i]*/
}
int maxIndex = checkMaxIndex(freq); // This Method returns an int that is the index of the highest frequency;
printArray(a);
System.out.println("The number with most freq digit is: " + a[maxIndex]);
}
非常感谢大家的帮助。
最佳答案
请将此视为一个指针,但我会首先计算一个整数中的数字!
/**
* Take a decimal number as input, count the digits.
*
* @param in
* A decimal number.
* @return An array of 10 digit counts.
*/
public static int[] digitCounter(int in) {
int[] ret = new int[10];
String v = String.valueOf(in);
for (char c : v.toCharArray()) {
// You should probably use a 'switch' here.
if (c == '0') {
ret[0]++;
} else if (c == '1') {
ret[1]++;
} else if (c == '2') {
ret[2]++;
} else if (c == '3') {
ret[3]++;
} else if (c == '4') {
ret[4]++;
} else if (c == '5') {
ret[5]++;
} else if (c == '6') {
ret[6]++;
} else if (c == '7') {
ret[7]++;
} else if (c == '8') {
ret[8]++;
} else if (c == '9') {
ret[9]++;
}
}
return ret;
}
关于Java-数组 : How do i find the number that has a similar digit most times?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295637/