Java中如何编写if条件判断3元素数组恰好有2个奇数
三元素int数组恰好2个奇数的判断条件实现
else if分支需要覆盖所有「两奇一偶」的组合场景,由于前置分支已经拦截了三个数全为奇数的情况,将三种两奇一偶的情况用逻辑或连接即可,填入的条件如下:
(test[0] % 2 != 0 && test[1] % 2 != 0 && test[2] % 2 == 0) || (test[0] % 2 != 0 && test[2] % 2 != 0 && test[1] % 2 == 0) || (test[1] % 2 != 0 && test[2] % 2 != 0 && test[0] % 2 == 0)
补全后的完整代码片段:
int[] test = {1, 2, 3}; if (test[0] % 2 != 0 && test[1] % 2 != 0 && test[2] % 2 != 0) { System.out.println("All numbers odd"); } else if ((test[0] % 2 != 0 && test[1] % 2 != 0 && test[2] % 2 == 0) || (test[0] % 2 != 0 && test[2] % 2 != 0 && test[1] % 2 == 0) || (test[1] % 2 != 0 && test[2] % 2 != 0 && test[0] % 2 == 0)) { System.out.println("2 numbers odd"); }
通用扩展写法
如果后续数组长度可能调整,硬编码元素组合的维护成本较高,可以先遍历数组统计奇数总数量,再根据计数结果判断:
int oddCount = 0; for (int num : test) { if (num % 2 != 0) { oddCount++; } } if (oddCount == 3) { System.out.println("All numbers odd"); } else if (oddCount == 2) { System.out.println("2 numbers odd"); }
内容的提问来源于stack exchange,提问作者Kadre Dobson
相关产品推荐
相关产品推荐

