gpt4 book ai didi

java - 如何从命令行查找数组中最常重复的数字?

转载 作者:行者123 更新时间:2023-12-02 07:03:15 26 4
gpt4 key购买 nike

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

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

}}

最佳答案

你的第二个循环中的逻辑有缺陷。另外,您还没有为数组中的所有数字分配空间,为此您需要一个 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.";

关于java - 如何从命令行查找数组中最常重复的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16387499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com