gpt4 book ai didi

java - 异常(exception)情况

转载 作者:行者123 更新时间:2023-11-30 06:43:02 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com