我正面临着控制结构的问题

时间:2018-02-04 15:31:29

标签: java

我的问题是输出我的代码。当我输入20时,输出必须怪异,但我得到并不奇怪。与值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);
    }
}

3 个答案:

答案 0 :(得分:1)

  

输出必须很奇怪,但我并不奇怪

因为,if(n%2 == 1)返回false并落入else阻止

if(n <= 2 && n >= 5) is `false`

else if(n <= 6 && n >= 20) is also `false` 

所以,再次落到else块。你可能会改变

if(n <= 2 && n >= 5)

if(n >= 2 && n <= 5)

else if(n <= 6 && n >= 20)

else if(n >= 6 && n <= 20)

否则,它们将永远不会true,并且始终属于else

答案 1 :(得分:0)

在您的程序中,最后else正在执行。将&&(逻辑 AND )更改为||(逻辑 OR ),这将检查数字是否小于高于OR的数字一些事情,而不是检查某事物是否小于或等于5 AND高于或等于20,同时在任何情况下都无法评估。

答案 2 :(得分:0)

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);
    }
}