我3在陣列中有值。
如何撰寫if陳述句來檢查數字是否2為3奇數以列印訊息?
代碼:
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 (condition) { //what will go here as a condition
System.out.println("2 numbers odd");
}
那么什么可以用來檢查數字是否為2奇數呢?3
uj5u.com熱心網友回復:
嘗試這個。
int[] test = {1, 2, 3};
switch (IntStream.of(test).map(i -> i & 1).sum()) {
case 3: System.out.println("All numbers odd"); break;
case 2: System.out.println("2 numbers odd"); break;
}
輸出:
2 numbers odd
uj5u.com熱心網友回復:
一種非常直接的方法是計算回圈中奇數元素的數量,然后將數字傳遞給條件。
這就是如何使用 Java 14 switch 運算式以簡潔的方式完成它:
public static void main(String[] args) {
int[] test = {1, 2, 3};
int oddCount = 0;
for (int next : test) {
if (next % 2 != 0) oddCount ;
}
switch (oddCount) {
case 1 -> System.out.println("1 number is odd");
case 2 -> System.out.println("2 numbers are odd");
case 3 -> System.out.println("All numbers are odd");
}
}
另一種方法是獲得這些數字的總和。
2如果這些3數字恰好是奇數,則意味著它們的總和應該是偶數。
因此,檢查總和是否為偶數并且至少第一個2陣列元素中的一個為奇數就足夠了:
public static void main(String[] args) {
int[] test = {1, 2, 3};
long sum = 0; // sum is of type `long` to guard against `int` overflow
for (int next : test) {
sum = next;
}
if (sum % 2 != 0 && test[0] % 2 != 0 && test[1] % 2 != 0) {
System.out.println("All numbers are odd");
}
else if (sum % 2 == 0 && (test[0] % 2 != 0 || test[1] % 2 != 0)) {
System.out.println("2 numbers are odd");
}
else if (sum % 2 != 0) {
System.out.println("1 number is odd");
}
}
uj5u.com熱心網友回復:
所以首先我們將計算所有可能的場景:
- 甚至都
- 都很奇怪
- 1 個奇數(2 個偶數)
- 2 個奇數(1 個偶數)
然后我們使用 intStream 函式來計算奇偶數。
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
int[] test = {2,5,3};
if (IntStream.of(test).noneMatch(num -> num % 2 == 0)) // All odd
{
System.out.println("All numbers odd");
}
else if (IntStream.of(test).noneMatch(num -> num % 2 == 1)) // All even
{
System.out.println("All numbers even");
}
else if(IntStream.of(test).sum()%2==1)
{
System.out.println("1 number is odd");
}
else{
System.out.println("2 numbers are odd");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/492171.html
上一篇:Pyspark條件陳述句
下一篇:elseif陳述句創建一個新列
