2014-09-23 159 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