我需要從命令行取單個數字的整數,並將它們放入數組中,然後查找最頻繁的整數。有時這個程序似乎有效,而其他時間則不行。如何從命令行中找到數組中最頻繁重複的數字?
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);
}}
當它不起作用時會發生什麼? – Keppil 2013-05-05 18:09:42
我遇到了數組綁定錯誤,我認爲這是打印輸入數字的次數,而不是顯示那個數字。我相信我現在已經修復了 – dcole617 2013-05-05 18:36:28