使用下面的代码,即使我输入了一个大于18的数字,我也会得到这个结果。
你多大了? 21岁还没到法定年龄呢!构建成功(总时间:3秒)
我是java的新手,正在尝试自学,有人能帮我吗?
import java.util.Scanner;
public class Chapter8 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner (System.in);
// TODO code application logic here
//Excercise 15
System.out.print("How old are you? ");
int x = Integer.parseInt(reader.nextLine());
if (x > 18){
System.out.println("You have not reached the age of Majority yet!");
}else {
System.out.println("You have reached the age of Majority!");
}发布于 2013-11-08 23:49:02
你的代码当前是这样的:“如果年龄大于18岁(即19岁或更高),那么他们就不是年龄”。
我想你指的是x < 18
发布于 2013-11-08 23:51:39
应该是另一种方式:
if (x < 18){
System.out.println("You have not reached the age of Majority yet!");
}else {
System.out.println("You have reached the age of Majority!");
}发布于 2013-11-08 23:53:28
您创建了一个语句,该语句仅在x> 18时才会打印一行。您应该使用else if语句来结束该语句。
public static void main(String[] args) {
Scanner reader = new Scanner (System.in);
// TODO code application logic here
//Excercise 15
System.out.print("How old are you? ");
int x = Integer.parseInt(reader.nextLine());
if (x > 18){
System.out.println("You have not reached the age of Majority yet!");
}
else if (x <= 17){
System.out.println("You have reached the age of Majority!");
}}
https://stackoverflow.com/questions/19863069
复制相似问题