如何在数组中从命令行中找到最常重复的数字?

时间:2013-05-05 18:08:54

标签: java

我需要从命令行获取单个数字的整数并将它们放入一个数组中,然后找到最常用的整数。有时这个程序似乎有效,有时则不然。

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);

} }

3 个答案:

答案 0 :(得分: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.";

答案 1 :(得分: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");

答案 2 :(得分:0)

以下是查找最常用号码的实现。

#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;
}