Java代码中的java.util.NoSuchElementException

时间:2015-10-14 06:06:29

标签: java exception

我得到了这个例外:

Please provide width: 4
Please provide height: Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at rr.fr.op.lab.prob1.Rectangle.scanner(Rectangle.java:51)
    at rr.fr.op.lab.prob1.Rectangle.main(Rectangle.java:31)

我的代码是:

package rr.fr.op.lab.prob1;
import java.util.Scanner;
public class Rectangle {

    public static void main(String[] args) {            

        if(args.length != 2 && args.length != 0){
            System.err.println("Invalid number of arguments was provided.");
            System.exit(1);

            double a = Double.parseDouble(args[0]);
            double b = Double.parseDouble(args[1]);

            double area = area(a,b);
            double perimeter = perimeter(a,b);

            System.out.println("You have specified a rectangle of width " + a + " and height "
                + b + ". Its area is " + area + " and its perimeter is " + perimeter);
        }

        double x,y,z;
        if(args.length == 0){
            System.out.printf("Please provide width: ");
            x = scanner();
            System.out.printf("Please provide height: ");
            y = scanner();
        }
    }

    private static double area(double a, double b){
        return a*b;
    }

    private static double perimeter(double a, double b){
            return 2*(a+b);
    }

    private static double scanner (){
        Scanner sc = new Scanner (System.in);
        double number = sc.nextDouble();
        sc.close();
        return number;  
    }
}

之后,我想使用方法trim()来删除空格。那可能吗?而且,我也需要isEmpty()方法。此代码必须计算矩形的面积和周长。输入是表格键盘或命令行。

3 个答案:

答案 0 :(得分:2)

使用后关闭扫描仪。在这种情况下,这也会关闭基础流System.in,因为它实现了Closeable

下次创建扫描仪时,System.in已经关闭,因此您无法从中读取更多元素。

创建一个扫描仪并多次重复使用。

如果你没有打开它(或者你可能泄露了参考文献),关闭一个流被认为是一种不好的做法。

可能还有其他代码依赖于流被打开,因此关闭它可能会导致代码失败。远离原因的失败是众所周知的难以调试。

不幸的是,很容易无意中关闭流,因为像Scanner,BufferedInputStream等类在它们关闭时会关闭它们的基础流。

答案 1 :(得分:1)

您基本上可以将scanner对象传递给您的方法,并在完成scanner()方法之外的扫描后关闭它。

...
if (args.length == 0) {
    Scanner sc = new Scanner(System.in);
    System.out.printf("Please provide width: ");
    x = scanner(sc);
    System.out.printf("Please provide height: ");
    y = scanner(sc);
    sc.close();
}
...

private static double scanner(Scanner sc){
    double number = sc.nextDouble();
    return number;  
}

答案 2 :(得分:0)

Scanner sc = new Scanner(System.in);
System.out.println("Please provide width: ");
int number1 = 0;
try {
    number1 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}

System.out.println("Please provide height:");
int number2 = 0;
try {
    number2 = Integer.parseInt(sc.nextLine());
} catch (IllegalArgumentException e) {
    e.printStackTrace();
}