好的,所以当我运行代码时,在输入no或任何false之后,我的程序不会跳转到底部的Else语句(嵌套的if_Else语句之外)我做错了什么?我尝试用else if (yes!=true)或else (!yes)初始化它,我的意思是你命名它,包括改变初始参数和输入(yes ==true ^ no==true)然而,定义另一个布尔变量为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 {
}
要使程序根据用户输入作出决定,必须查看txt
的值。
把你的代码改成这样:
yes = txt.equalsIgnoreCase("yes");
if (yes == true) {
...
} else {
...
}
或者更短:
if (txt.equalsIgnoreCase("yes")) {
...
} else {
...
}