1

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

代码:

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)

>

谢谢

布赖恩

4

2 回答 2

1

问题是关闭stdin也会关闭底层流,在这种情况下,System.in. 因此,您将无法从中获得更多输入。您需要阻止它关闭。最简单的选择可能是System.inCloseShieldInputStream.

于 2013-06-23T01:43:08.137 回答
1

正如@MikePrecup 所说,当您关闭第一个 Scanner ( stdin) 时,您也在关闭System.in,因此第二个 Scanner 无法再从中读取并NoSuchElementException抛出 a 。

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

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
于 2013-06-23T01:51:54.553 回答