我正在尝试做这个挑战https://www.hackerrank.com/challenges/java-if-else
我尝试这样做:
public class Main {
public static void main(String[] args) {
int x;
x = 34;
if ((x % 2) != 0) {
System.out.println("Weird");
} else if (((x % 2 == 0) & ((x >= 2) & (5 >= x)))) {
System.out.println("Not Weird");
} else if (((x % 2 == 0) & ((x >= 6) & (20 >= x)))) {
System.out.println("Weird");
} else if ((x % 2 == 0) & (x > 20)) {
System.out.println("Not Weird");
}
}
}
我在 Intellij 中运行了这个,它运行良好,但在这里,我只得到了三个测试用例的正确结果。我究竟做错了什么?我对扫描仪的内容感到不知所措,因为我什至在自己的阅读中还没有涉及到这些内容。
最佳答案
HackerRank challenge, what am I doing wrong?
您没有从标准输入读取数字,因此测试都在检查数字 34 的输出。
替换
int x;
x = 34;
有了这个(这是测试的开始)
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
这样做,你的测试就会顺利通过。
<小时/>替代解决方案
boolean even = x % 2 == 0;
boolean weird = !even || (even && (6 <= x && x <= 20));
System.out.println(weird ? "Weird" : "Not Weird");
关于java - HackerRank 挑战,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006991/