我不知道为什么这个例外不起作用......
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();
}
}
答案 0 :(得分:1)
我认为你的意思是Condition
而不是Exception
,但是,你没有得到预期结果的原因是因为if-statements
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-statements
的优先级,如下所示:
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");
}