// this is my code
import java.util.*;
public class conditional {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
if(age>=18){
System.out.println("you are eligible to vote,drive,drink");
}
if(age>=13 && age<18){
System.out.println("you are teenager");
}
else{
System.out.println("you are not an adult");
}
}
}
这是我遇到的错误
20
you are eligible to vote,drive,drink
you are not an adult
当我进入 17 岁的时候,这表明你已经是青少年了 当我进入12岁的时候,这表明你还不是成年人 当我输入年龄 18 岁或超过 18 岁时,这表明你们都有资格投票、开车、喝酒 你还不是成年人
这不是一个错误。 这就是预期的输出。 此代码产生一行输出:
if (age >= 18) {
System.out.println("you are eligible to vote,drive,drink");
}
这段代码会产生另一行输出
if (age >= 13 && age < 18) {
System.out.println("you are teenager");
} else {
System.out.println("you are not an adult");
}
在后面的代码中,两个可能的输出是互斥的。 也就是说,对于任何给定的代码执行,您只会看到其中一行输出或另一行,而不会同时看到两者。
但这与第一个
if
陈述无关。 这两个 if
块没有以任何方式连接或逻辑相关。
如果您希望所有三个的块相互排斥,那么您需要将它们在一个更大的结构中相互连接。 为此,您正在寻找
else if
。 (从技术上来说,这不是它自己的关键字,它只是将整个下一个 if
块放入前一个 else
块的 if
中。)例如:
if (age >= 18) {
System.out.println("you are eligible to vote,drive,drink");
} else if (age >= 13 && age < 18) {
System.out.println("you are teenager");
} else {
System.out.println("you are not an adult");
}