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。我尝试了 i modulus 2 不能等于 0,但没有看到任何变化。
我需要改变什么?谢谢。
最佳答案
错误是这一行:
int modeOdd = 0;
您应该声明 modeOdd = 1
,因为当前您将其声明为 0,这不是奇数,因此如果 ary[0]
包含的值大于中的任何值奇数索引,它永远不会改变。
注意:数组长度小于2时要小心
关于java - 如何在数组中搜索奇数索引元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25988018/