如何在 Java 中找到数组中的奇数和偶数?
在循环检查中,每个元素上 i%2 运算的结果如果为 0,则该元素为偶数,否则为奇数。
示例
public class OddNumbersInAnArray { public static void main(String args[]) { int[] myArray = {23, 93, 56, 92, 39}; System.out.println("Even numbers in the given array are:: "); for (int i=0; i<myArray.length; i++) { if(myArray[i]%2 == 0) { System.out.println(myArray[i]); } } System.out.println("Odd numbers in the given array are:: "); for (int i=0; i<myArray.length; i++) { if(myArray[i]%2 != 0) { System.out.println(myArray[i]); } } } }
输出
Even numbers in the given array are:: 56 92 Odd numbers in the given array are:: 23 93 39
广告