簡體   English   中英

如何在數組中搜索奇數索引元素

[英]How to search odd index elements in an array

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並且看不到任何變化。

我需要更改什么? 謝謝。

錯誤是這一行:

int modeOdd = 0;

您應該聲明modeOdd = 1 ,因為當前您將其聲明為0,這不是奇數,因此,如果ary[0]包含的值大於奇數索引中的任何值,則它永遠不會改變。

注意 :如果數組的長度小於2,請小心

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM