如何在 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
广告