如果答案是这个,不要问这个



所以我想这样做,如果你对一个问题给出一个特定的答案,它会跳过其他问题。 这是我目前的代码:


System.out.print("How old are you? ");
int age = Integer.parseInt(scanner.nextLine());
System.out.print("Do you already have a scooter license? ");
String scooter = scanner.nextLine();
System.out.print("Do you already have a car license? ");
String auto = scanner.nextLine();
if (age >= 17 && auto.equals("no") || age >= 17 && auto.equals("No")) {
System.out.println("You can get a car license.");
} else if (age >= 17 && auto.equals("yes") || age >= 17 && auto.equals("Yes")){
System.out.println("You can also buy a scooter.");
} else if (age == 16 && scooter.equals("no") || age == 16 && scooter.equals("No")) {
System.out.println("You can get a scooter license.");
} else if (age == 16 && scooter.equals("yes") || age == 16 && scooter.equals("Yes")) {
System.out.println("You can get a car license next year.");
} else if (age < 16) {
System.out.println("When you are 15.5 years old you can do your written exam for a scooter license.");
System.out.println("And when you're 16 you can get a scooter license.");
}
}

所以我想要的是,当你回答第一个问题低于 16 分的任何内容时,你跳过其他 2 个问题。

如果你对第一个问题回答 16,你跳过第三个问题。

如果你对第一个问题的回答是17分或更高,你会跳过第二个问题。

你可以帮我吗?

有一个简单的方法可以做到这一点。 通过在其他问题周围添加一个简单的 if 语句。

System.out.print("How old are you? ");
int age = Integer.parseInt(scanner.nextLine());
if(age > 15)
{
if(age == 16)
{
System.out.print("Do you already have a scooter license? ");
String scooter = scanner.nextLine();
}
if(age > 16)
{
System.out.print("Do you already have a car license? ");
String auto = scanner.nextLine();
}
}

如果他们回答了 15 个或更少,则会跳过接下来的两个问题。 如果他们回答16,它只会问他们关于踏板车的问题。 如果他们回答超过16,它将跳过踏板车并询问汽车。

首先 - 你可以使用 toLowerCase(( 方法。任何答案都将被编辑为小写,因此您无需检查答案中的小写/大写(等于"否",等于"否"(。

您也可以退出函数,使用returnSystem.exit(0);退出项目。

你也可以使用'?:"的方式,来提高代码的可读性

System.out.print("How old are you? ");
int age = Integer.parseInt(scanner.nextLine());
if (age < 16) {
System.out.println("When you are 15.5 years old you can do your written exam for a scooter license.");
System.out.println("And when you're 16 you can get a scooter license.");
//return; / System.exit(0); - can use this way
} else  if (age == 16) { //or this
System.out.print("Do you already have a scooter license? ");
String scooter = scanner.nextLine();
System.out.println(scooter.toLowerCase().equals("no") ? 
"You can get a scooter license." //if yes
: "You can get a car license next year."); //if no
} else {
System.out.print("Do you already have a car license? ");
String auto = scanner.nextLine();
System.out.println(auto.toLowerCase().equals("no") ? 
"You can get a car license." 
: "You can also buy a scooter.");
}

相关内容

最新更新