Java util扫描器throwforunknown源错误(错误类型输入) [英] java util scanner throwforunknown source error (cant type input)

查看:179
本文介绍了Java util扫描器throwforunknown源错误(错误类型输入)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的扫描仪有问题,我真的不知道怎么了.我有一个Circle类,我想在构造函数上对其半径进行检查循环.这是代码:

I have a problem with a scanner and I don't really know what's wrong. I have a Circle class and I want to make check loop for its radius on the constructor. Here is the code:

Circle(double x, double y, String color, double radius) {
    super(x, y, color); // constructor from class shape which is extended by circle
    Scanner r = new Scanner(System.in);

    while (radius <= 0)
    {
        System.out.println("radius has to be > 0.....Give radius again");
        if (r.hasNextDouble())
        {
            radius = r.nextDouble();
        }
        else
        {
            r.nextLine(); //25th line
        } 
    }
    this.radius = radius;
    r.close();
}

如果我将半径设置为0,则没有机会进行输入,它会显示以下消息:

If I put as a radius 0 I don't get the chance to make an input and it gives me this message:

radius has to be > 0.....Give radius again
Exception in thread "main" java.util.NoSuchElementException:No line found
at java.util.Scanner.nextLine(Unknown Source)
at pack.Circle.<init>(Circle.java:25)
at pack.Main.main(Main.java:11)

怎么了?

推荐答案

Scanner.nextLine() throws the NoSuchElementException if it couldn't read a line from the provided InputStream. Since you're using System.in as your input stream and since it will block the thread until it could read the requested line, there is only one reason left, which can cause such a problem: the stream is already closed.

您正在呼叫 Scanner.close() 在您的Circle构造函数中,它将不仅关闭扫描程序,还将关闭使用的输入流.这意味着变量System.in引用的输入流已关闭,无法再次打开.因此,如果您已经创建了一个圆,或者在代码中的其他位置关闭了流,则将得到所提到的异常.

You're calling Scanner.close() in your Circle constructor, which will not only close the scanner, it will also close the used input stream. That means, the input stream, referenced by the variable System.in is closed, and can't be opened again. So if you already created a circle, or closed the stream somewhere else in your code you will get the mentioned exception.

要解决此问题,只需删除每个阅读器的每个close调用,例如

To fix the problem, just remove every close call for every reader, like Scanner or BufferedReader, which uses System.in as its source stream.

然后您应该考虑将r变量提取到专用类中.然后,您可以创建Scanner 一次,并在需要用户输入的任何地方使用它.如果您要关闭应用程序并执行清除操作,则可以关闭该扫描仪.

And then you should think about extracting the r variable into a dedicated class. Then you can create the Scanner once and use it everywhere where you want to request user input. You can close that scanner if you like to close the application and perform a cleanup.

这篇关于Java util扫描器throwforunknown源错误(错误类型输入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆