java - 异常(exception)情况

标签 java if-statement exception

我不知道为什么这个异常不起作用......

import java.util.*;

public class a {
    public static void main(String[] args) {
        Scanner a = new Scanner(System.in);
        int x; 
        x=a.nextInt();
        if( x < 5) {
            System.out.print("This is if statement");
        }else if(x<3){
            System.out.print("This is else if statement");
        }else{
           System.out.print("This is else statement");
        }
        a.close();
    }
}

最佳答案

我相信您的意思是条件而不是异常,但是,您没有得到预期结果的原因是您的逻辑和优先级错误>if 语句

if( x < 5) { // any input less than 5 will execute this if statement and will NOT proceed to the next blocks
     System.out.print("This is if statement");
}else if(x<3){ // this is not reachable because the first if statement will catch all inputs less than 5 INCLUDING those less than 3
     System.out.print("This is else if statement");
}else{
     System.out.print("This is else statement");
}

要修复它,只需修复 if 语句 的优先级,如下所示:

if( x < 3) { // this should come first
     System.out.print("This is if statement");
}else if(x<5){
     System.out.print("This is else if statement");
}else{
     System.out.print("This is else statement");
}

关于java - 异常(exception)情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098167/

相关文章:

performance - Python 2.7 : List comprehension with "if-statement" runs very slowly

c++ - 为什么异常规范没有用?

android - java util 压缩 ZipException : duplicate entry

c++ - 异常后清理

java - 如何为返回 json 对象的字符串表示形式的函数编写常规测试用例?

java - post 方法没有得到 payload 对象

java - Easymock:mock正在执行

c++ - for循环内的if语句未执行

Java:重载构造函数之间的选择

javascript - 选择单选按钮值时显示警报