NoSuchElementException:找不到行

时间:2015-12-17 03:37:11

标签: java

我正在学习通过TMC MOOC编写java代码。我是初学者,正在寻找关于这个问题的一些意见。每次运行此代码时,我都会收到错误NoSuchElementException:No Line Found。有什么帮助吗?

import java.util.Scanner;

public class AgeOfMajority {

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.print ("How old are you? ");
    int age = Integer.parseInt (reader.nextLine());

    if (age < 18) {
        System.out.println ("You have not reached the age of majority yet!");

        System.out.print ("How old are you?");
        int age2 = Integer.parseInt (reader.nextLine());

        if (age2 >= 18) {
            System.out.println ("You have reached the age of majority!");
        }

    }                        

}

}       

1 个答案:

答案 0 :(得分:0)

从语法角度来看,此代码是正确的。

然而,你可以做一些小改变

  1. 您可以使用nextInt()而非使用readLine(),然后必须解析为整数

  2. 您的代码最多只能有两个条目。这可以更改为循环以继续输入年龄,直到输入最大年龄。例如,

  3. while (age < 18){ System.out.println("You have not reached the age of majority! "); System.out.print("How old are you? "); age = reader.nextInt(); }

    但是,您需要添加终止条件以停止程序执行。

相关问题