[英]I'm facing an issue with control structures
My problem is with output of my code. 我的问题是我的代码输出。 When I enter 20, the output must be weird , but I am getting not weird .
当我输入20时,输出一定很奇怪 ,但是我却变得很奇怪 。 Same with the value 18.
与值18相同。
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
输出一定很奇怪,但我却不奇怪
Because, if(n%2 == 1)
return false
and fall to else
block where 因为,
if(n%2 == 1)
返回false
并落入else
块,其中
if(n <= 2 && n >= 5) is `false`
and 和
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else
block. 因此,再次落入
else
块。 You probably change 你可能会改变
if(n <= 2 && n >= 5)
to 至
if(n >= 2 && n <= 5)
and 和
else if(n <= 6 && n >= 20)
to 至
else if(n >= 6 && n <= 20)
Otherwise, they will never be true
and always falls to else
. 否则,它们将永远不会是
true
并且永远会落到else
。
In your program last else
is being executed. 在您的程序中正在执行
else
操作。 Change &&
(logical AND ) to ||
将
&&
(逻辑AND )更改为||
(logical OR ) which will check if number is less than something OR
higher than something, instead of checking if something is less or equal 5 AND
higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case. (逻辑或 ),这将检查是否数量小于东西
OR
不是一些更高,而不是检查,如果事情是小于或等于5 AND
在相同的时间高于或等于20,因为它不具有可能性在任何评价案件。
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.