从方法中使用java.util.Scanner会导致运行时错误 [英] Using a java.util.Scanner from within a method causes a runtime error

查看:88
本文介绍了从方法中使用java.util.Scanner会导致运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码会给我一个运行时错误?第二次调用该方法时,它给了我一个NoSuchElementException.如果我删除对stdin.close()的调用,效果很好,但是Eclipse发出警告,指出资源未关闭.

Why would the following code give me a runtime error? It gives me a NoSuchElementException when the method is called the second time. It works fine if I delete the call to stdin.close(), but then Eclipse gives a warning that the resource is not closed.

import java.util.Scanner;


public class st {
  public static void main(String[] args) {
    System.out.println("First call");
    getInt("Enter first int (1-10): ");
    System.out.println("Second call");
    getInt("Enter second int (1-10): ");
  }

  /**
   * Reads an integer number from the keyboard.
   *
   * @param  prompt    the string to display as a prompt.
   * @return           the integer number entered at the keyboard.
   */
  public static int getInt(String prompt) {
    Scanner stdin = new Scanner(System.in);

    System.out.print(prompt);
    int val = stdin.nextInt();

    stdin.close();
    return(val);
  }
}

// END

输出:

>java st
First call
Enter first int (1-10): 5
Second call
Enter second int (1-10): 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.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at st.getInt(st.java:24)
        at st.main(st.java:9)

>

版本:

>java -version
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

>

谢谢

布莱恩

推荐答案

AS @MikePrecup说,当您关闭第一个扫描仪(stdin)时,您也正在关闭System.in,因此第二个扫描仪无法再读取从中抛出NoSuchElementException.

AS @MikePrecup says, when you close the first Scanner (stdin), you are also closing System.in, therefore the second Scanner can no longer read from it and a NoSuchElementException is thrown.

但是,我建议另一个选择:使用单个扫描程序将其声明为类变量.

However, I would suggest another option: use a single scanner declaring it as a class variable.

public class st {

  private static Scanner stdin = new Scanner(System.in);

  public static void main(String[] args) {
    System.out.println("First call");
    getInt("Enter first int (1-10): ");
    System.out.println("Second call");
    getInt("Enter second int (1-10): ");
  }

  /**
   * Reads an integer number from the keyboard.
   *
   * @param  prompt    the string to display as a prompt.
   * @return           the integer number entered at the keyboard.
   */
  public static int getInt(String prompt) {
    System.out.print(prompt);
    int val = stdin.nextInt();

    stdin.close();
    return(val);
  }
}

// END

这篇关于从方法中使用java.util.Scanner会导致运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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