0

我需要从命令行中取出一位整数并将它们放入一个数组中,然后找到最常见的整数。有时这个程序似乎工作,而其他时候,它没有。

public class MostFrequent {
    public static void main(String[] args){
    int num=0;
    int[] freq= new int[9];//intialize array for integers 0-9
    for (int i=0; i<args.length; i++){
      try {
        num = Integer.parseInt(args[i]);
        freq[num]++;//adds to array counter
        }
        catch (NumberFormatException nfe) {
        }
    }
    int max=0,j;
    for (j=0; j<10; j++){
      while(freq[j]>max){
        max=freq[j];
      }
    }
    System.out.println("The digit that appears most frequently is " + freq[j]);
  }
}

感谢大家的帮助,这最终对我有用,并且感谢提到使阵列更加动态的人,这也有所帮助。这是我完成的代码:

    public class MostFrequent {
public static void main(String[] args){
int num=0;
int[] freq= new int[args.length];//intialize array for integers 0-9
for (int i=0; i<args.length; i++){
  try {
    num = Integer.parseInt(args[i]);
    freq[num]++;//adds to array counter
    }
    catch (NumberFormatException nfe) {
    }
}
int max=0,j;
for (j=1; j<args.length; j++){
  while(freq[j]>freq[max]){//compares a max array val to the previous val
    max=j;
  }
}
System.out.println("The digit that appears most frequently is " + max);

} }

4

3 回答 3

2

第二个循环中的逻辑有缺陷。此外,您还没有为数组中的所有数字分配空间,您需要一个空间int[10]。解决它的一种方法是这样的:

int[] freq = new int[10];//intialize array for integers 0-9

...

int maxindex = 0;
for (int j = 1; j < 10; j++){
    if (freq[j] > freq[maxIndex]) {
        maxIndex = j;
    }
}
System.out.println("The digit that appears most frequently is " + j + ", that appears " + freq[j] + " times.";
于 2013-05-05T18:12:26.750 回答
0

Here is the implementation to find most frequent number.

#include<iostream>
using namespace std;

// Returns maximum repeating element in arr[0..n-1].
// The array elements are in range from 0 to k-1
int maxRepeating(int* arr, int n, int k)
{
// Iterate though input array, for every element
// arr[i], increment arr[arr[i]%k] by k
for (int i = 0; i< n; i++)
    arr[arr[i]%k] += k;

// Find index of the maximum repeating element
int max = arr[0], result = 0;
for (int i = 1; i < n; i++)
{
    if (arr[i] > max)
    {
        max = arr[i];
        result = i;
    }
}

/* Uncomment this code to get the original array back
   for (int i = 0; i< n; i++)
      arr[i] = arr[i]%k; */

// Return index of the maximum element
return result;
}

// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 8;

cout << "The maximum repeating number is " <<
     maxRepeating(arr, n, k) << endl;

return 0;
}
于 2014-04-15T18:09:47.847 回答
0

改变你的循环

int max=freq[0];
int maxIndex = 0;
for (j=1; j<10; j++){
  if(freq[j]>max)
  {
    max=freq[j];
    maxIndex = j;
  }
}

另外,你有错误的输出。

而不是(这会给你最后一个数字)

System.out.println("The digit that appears most frequently is " + freq[j]);

使用(打印最大数量及其出现次数)

System.out.println("The digit that appears most frequently is " + maxIndex + " - " + max + "x");
于 2013-05-05T18:13:46.800 回答