Java:尝试(扫描仪扫描=新的扫描仪(System.in){}导致异常 [英] Java: try(Scanner scan = new Scanner(System.in) { } causing an exception

查看:192
本文介绍了Java:尝试(扫描仪扫描=新的扫描仪(System.in){}导致异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用尝试(扫描仪扫描=新的扫描仪(System.in)){} 导致


线程main中的异常java.util.NoSuchElementException

Exception in thread "main" java.util.NoSuchElementException

当我尝试调试它时, p>

When I try to debug it says that


变量信息不可用,源编译时没有-g选项。

Variable information not available, source compiled without -g option.

并显示以下代码

    public Scanner(InputStream source) {
    this(new InputStreamReader(source), WHITESPACE_PATTERN);
  }

我使用这一行的方法之一:

One of my methods that uses this line:

protected String loginName(){
    String username;
    String password;
    try (Scanner scan = new Scanner(System.in)) { // This line is causing the error.
      System.out.print("Enter Username: ");
      username = scan.next();
      System.out.print("Enter Password: ");
      password = scan.next();
    }
    if(getUsernamesList().contains(username))

        if(password.equals(getPasswordsList().get(getUsernamesList().indexOf(username)))) return username;
        else return "-1";

    else return "-1";
}


推荐答案

c $ c> System.in (全局变量)。 ,不要这样做。每个地方你有

You're closing System.in (a global-variable). Please, do not do that. Everywhere you have

try(Scanner scan = new Scanner(System.in))

保证 System.in 关闭(d)。一旦它是关闭(d)你不能再读取(或者你得到你提到的异常)。此外,您可以使用调试符号进行编译(或使用IDE的内置调试器或 jdb )。 扫描仪。关闭() Javadoc说(部分),

guarantees that System.in will be close(d). Once it's close(d) you can't read from it again (or you get your mentioned Exception). Also, you can compile with debug symbols (or step into it with your IDE's built-in debugger or jdb as applicable). The Scanner.close() Javadoc says (in part),


如果此扫描仪尚未如果底层的可读的也实现了 关闭 接口然后可读的关闭方法将被调用

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked

这篇关于Java:尝试(扫描仪扫描=新的扫描仪(System.in){}导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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