我对 if else 语句有疑问。要求是:
- 如果 n 是奇数,则输出 Weird
- 如果 n 为偶数且在 2 到 5 的范围内,则输出 Not Weird
- 如果 n 为偶数且在 6 到 20 的范围内,则输出 Weird
- 如果 n 为偶数且大于 20,则输出 Not Weird。
当输入数字为18时,输出预计会奇怪。对于输入数字20也是如此。
import java.util.*;
public class Solution {
public static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
String ans = "";
if ((N % 2) == 1) {
ans += "Weird";
System.out.println(ans);
}
else if ((N % 2) == 0) {
if (N >= 2 || N <= 5) {
ans += "Not Weird";
System.out.println(ans);
}
}
else if ((N % 2) == 0) {
if (N >= 6 || N <= 20) {
ans += "Weird";
System.out.println(ans);
}
}
else if ((N % 2) == 0) {
if (N > 20) {
ans += "Not Weird";
System.out.println(ans);
}
}
}
}
编辑:但是当我输入数字 18 而不是 Weird 时,输出为 Not Weird.,数字 20 相同。
最佳答案
试试这个代码。
import java.util.*;
public class Solution {
public static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
String ans = "";
if ((N % 2) == 1) {
ans += "Weird";
} else {
if (N <= 5) {
ans += "Not Weird";
} else if (N <= 20) {
ans += "Weird";
} else {
ans += "Not Weird";
}
}
System.out.println(ans);
}
}
关于java - 使用if else语句扫描并打印奇数和偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61100016/