我不知道为什么这个异常不起作用......
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/