import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in);enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
} else{
System.out.println("Invalid age.");
}
}
}
当我输入一个负数时,它就属于&#34;你太年轻了,不能上电脑!!!!&#34;而不是显示&#34;无效年龄。&#34;我试过改变条件,但它似乎不起作用。
答案 0 :(得分:1)
由于负数小于12,您可以通过测试负值并通过依赖之前的if-else
检查来消除&&
块来简化您的int num = quest.nextInt();
if (num < 0) { // <-- negative values.
System.out.println("Invalid age.");
} else if (num <= 12) { // <-- (0, 12)
System.out.println("You are too young to be on the computer!!!!");
} else if (num <= 17) { // <-- (13, 17)
System.out.println("Welcome young teen");
} else if (num <= 60) { // <-- (18, 60)
System.out.println("Welcome adult");
} else { // <-- greater than 60
System.out.println("Welcome senior citizen!!");
}
块链检查条件。像,
{{1}}
答案 1 :(得分:0)
您应该使用if(Condition) { //Code }
语句将其作为第一个条件。好吧,我对代码进行了一次运行,并对你的代码进行了一些调整。
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in); //enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 0) {
System.out.println("Invalid age.");
} else if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
}
}
}