gpt4 book ai didi

java - 如何在 if、嵌套 if、else 语句中使用具有两种含义的 boolean 值

转载 作者:行者123 更新时间:2023-12-02 03:30:47 24 4
gpt4 key购买 nike

好吧,所以当我运行代码时,输​​入 no 或任何错误的内容后,我的程序不会跳转到底部的 Else 语句(在嵌套的 if_Else 语句之外)我做错了什么?我尝试用 else if (yes!=true) 或 Else (!yes) 启动它,我的意思是你命名它,包括更改初始参数和插补 ( yes==true ^ no==true) 但是,定义另一个 boolean 变量为 no 并设置为 true!

import java.util.Scanner;
public class Flights
{
public static void main(String args[]){
String txt;
boolean yes=true;

Scanner type=new Scanner(System.in);
int days;

System.out.println("Is this a round trip? ");
txt=type.next();

if(yes==true){
System.out.println("How many days in advance do you plan to book your flight?: ");
days=type.nextInt();
if(days>180)
System.out.println("Error: Flights can't be booked for more than 180 days out");

else if( days<=180 && days>=14)
System.out.println("Your flight cost is: $275");

else if(days<14 && days>=7)
System.out.println(" Your flight cost is: $320");

else if(days<7)
System.out.println("Your flight cost is: $440");
}
else
{
System.out.println("Enter your discount code");

}


}
}

最佳答案

好吧,您将 yes 变量初始化为 true,并且在开始比较 yes 值的条件语句之前没有对其进行任何更新true。这就是问题所在。

这是您开始的地方:

boolean yes=true;

然后等待用户输入,但不要更新 yes 值,而是继续像这样检查。

if(yes==true){
}

这会导致永远不会到达 else 语句。

<小时/>

你可以做的是,遵循这一行:

txt=type.next();

您可以更新 yes 变量的值,如下所示:

txt=type.next();  
yes = (txt != null) && "yes".equals(txt.toLowerCase());

if(yes==true){
//...
} else {
}

希望这有帮助。

关于java - 如何在 if、嵌套 if、else 语句中使用具有两种含义的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136651/

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