java中的扫描仪输入

时间:2018-03-26 18:45:22

标签: java java.util.scanner

我自学Java。在学习标准I / O的同时,我不断遇到以下错误。

Exception in thread "main" Enter first name : java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at FirstJavaHello.ex_2_3(FirstJavaHello.java:46)
    at FirstJavaHello.main(FirstJavaHello.java:67)

以下是我的代码

import java.util.Scanner;

public class FirstJavaHello {

    public static void ex_2_1() {
        int radius = 2;
        double area;
        final double pi = 3.142;
        area= pi * radius * radius;
        System.out.printf ("The area is: %f", area);
        //System.out.println(area);
    }

    public static void ex_2_2() {
        int radius;
        double area, pi;
        Scanner readInput = new Scanner(System.in);
        //extra line feed
        System.out.println();

        System.out.printf("Enter the radius: ");
        radius = readInput.nextInt();
        //readInput.nextLine();

        Scanner readPI = new Scanner(System.in);
        //System.out.println();
        System.out.printf("Enter the PI: ");
        pi = readPI.nextDouble();
        //readPI.nextLine();

        area= pi * radius * radius;
        System.out.printf("The area is: %f", area);

        readPI.close();
        readInput.close();
    }


    public static void ex_2_3() {
        System.out.println();
        Scanner readStr = new Scanner(System.in);
        String firstName;

        System.out.printf("Enter first name : ");
        //readStr.nextLine();
        firstName = readStr.next();

        System.out.printf("your name is %s ", firstName);   
        readStr.close();
}

public static void main(String [] args) {
    ex_2_1();
    ex_2_2();
    ex_2_3();
}

}

现在,如果我评论ex_2_2()函数调用它完全正常。我已经阅读过Javadoc,它说当下一行没有行时,Scanner会抛出异常。有人可以帮助更好地理解这个概念。

由于

0 个答案:

没有答案