0
我的代碼似乎有問題,因爲它沒有正確打印。我試圖使用我們爲類創建的另一種方法來查找數組的模式。查找數組的模式?
例如,一個包含元素{4,4,4,5,5}的數組,打印模式爲5而不是4.爲什麼?
public static int mode(int[] numbers) {
int winner = 0;
for(int i=1; i<numbers.length; i++){
winner = numbers[0];
if (occr(numbers,numbers[i]) == occr(numbers,numbers[i-1])){
winner = numbers[i];}
else if(occr(numbers,numbers[i]) > occr(numbers,numbers[i-1])){
winner = numbers[i];}
else if(occr(numbers,numbers[i]) < occr(numbers,numbers[i-1])){
winner = numbers[i-1];}
}
return winner;
}
public static int occr(int[] numbers, int x){
int counter = 0;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] == x){
counter++; }
}
return counter;
}
如果(值>贏家)方法將無法正常工作,因爲如果您有一個{4,4,5,5,5}的數組會怎麼樣? 3 <5&模式將是4而不是5? –