2014-09-23 183 views
0
int modeOdd = 0; 

System.out.println("Occurence of all existing ODD digits --"); 

    for (int i = 1; i < ary.length; i += 2) { // This prints the array element at the odd indices 
     if (ary[i] > 0) { 
     System.out.println("Digit " + i + " : " + ary[i]); 
     } 
    } 

    System.out.println("\nthe odd digit (s) that has/have the " 
      + "higest occurence-"); 



for (int i = 1; i < ary.length; i += 2){ 
    int newNumber = ary[i]; 
    if (newNumber > ary[modeOdd]) && (i % 2 != 0)){ 
     modeOdd = i; 
    } 
} 
System.out.println(modeOdd); 


} 

該代碼的第一部分工作並打印奇數索引處的數組元素。然而,代碼的第二部分是找到我所有數組元素的模式。我不明白爲什麼它會這樣做,因爲我在索引i處開始它,並將其增加2.我試着模數2不能等於0,也看不到任何更改。如何在一個數組中搜索奇數索引元素

我需要改變什麼?謝謝。

回答

3

bug是這一行:

int modeOdd = 0; 

你應該申報modeOdd = 1,你目前宣佈它爲0,這是不奇怪的,所以如果ary[0]包含值比奇數索引的任何值時,它會從不改變。

:小心如果數組的長度小於2

0
public class Test { 
    public static void main(String[] args) { 
     int modeOdd = 1; 

     int[] ary = new int[] { 2, 3, 4, 5, 6, 78, 9, 3 }; 
     System.out.println("Occurence of all existing ODD digits --"); 

     for (int i = 1 ; i < ary.length ; i += 2) { // This prints the array element at the odd indices 
      if (ary[i] > 0) { 
       System.out.println("Digit " + i + " : " + ary[i]); 
      } 
     } 

     System.out.println("\nthe odd digit (s) that has/have the " + "higest occurence-"); 

     for (int i = 1 ; i < ary.length ; i += 2) { 
      int newNumber = ary[i]; 
      if (newNumber > ary[modeOdd] && (i % 2 != 0)) { 
       modeOdd = i; 
      } 
     } 
     System.out.println(modeOdd); 

    } 
} 

輸出

Occurence of all existing ODD digits -- 
Digit 1 : 3 
Digit 3 : 5 
Digit 5 : 78 
Digit 7 : 3 

the odd digit (s) that has/have the higest occurence- 
5