【发布时间】:2013-11-30 18:50:11
【问题描述】:
我的一项任务有问题。 我被要求构建一个用户将输入长度的数组。 最后,主要目标是打印任何数字中频率最高的数字。 例如,如果数组的长度为 4,数字为:1000、212、1345、88818 - 应该打印的数字是 88818,因为它有更多相似的数字(数字 8 出现了 4 次)。
我确信我到目前为止所拥有的一切都很好,但我发现该程序不完整有两个原因:
- 如果数组的大小大于 2,则在创建数组后不会发生任何事情。
- 如果其中一个数字再次超过一位,则不会发生任何事情。
我已经尝试找出问题所在 5 个小时了,但仍然没有运气。 如果有人可以帮助我,我将不胜感激。
请注意,我不允许使用非 int[] 类型的数组,以及任何比数组更高级的材料。
这是我目前所拥有的:
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]);
}
非常感谢大家的帮助。
【问题讨论】: