0

使用下面的代码,即使我输入了一个大于 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!");
        }
4

3 回答 3

5

您的代码当前显示为“如果年龄大于 18 岁(即 19 岁或以上),则他们未达到年龄”。

我想你的意思是x < 18

于 2013-11-08T15:49:01.677 回答
0

应该反过来:

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-08T15:51:38.537 回答
0

你做了一个只有在 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!");
    }

}

于 2013-11-08T15:53:28.033 回答