这个问题已经在这里有一个答案:
我写了一个Java代码,使用谁使用扫描仪的几个方法。第一种方法效果不错,但第二个得到与错误堆栈
“Java.util.NoSuchElementException”。
第一种方法的maxPile的代码:
public static int maxPile() {
Scanner scan = new Scanner(System.in);
System.out.println("enter max number of piles");
int pMax = scan.nextInt();
scan.close();
return pMax;
}
第二种方法maxMatches的代码:
public static int maxMatches() {
Scanner scan = new Scanner(System.in);
System.out.println("enter max number of matches per pile");
int mMax = scan.nextInt();
scan.close();
return mMax;
}
该方法是相同的,但第一个工作,第二个不行...我的输出 -
enter max number of piles
8
enter max number of matches per pile
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 autoNim.autoNim.maxMatches(autoNim.java:89)
at autoNim.autoNim.main(autoNim.java:12)
(即“8”是我的输入,第12行呼叫的方法MaxMatches,线89是xint mMax=scan.nextInt();
从方法)
这是因为你关闭了扫描仪。关闭扫描仪始终关闭底层资源,即System.in
。你不能使用你System.in
关闭后,再向。
不要关闭扫描仪捆绑System.in
。
资源只应由谁打开他们一个被关闭。在JVM打开System.in
,它也将再次当你的程序完成后关闭它。你是不是负责管理System.in
,保持打开状态。
需要注意的是,如果你想关闭扫描仪,你必须确保它是异常安全的。即你需要的try-catch-终于把它包起来。如果可能的话,更愿意使用try-与资源:
try (Scanner scanner = new Scanner(...)) {
...
}
这在try块后会自动关闭它在一个异常安全的方式。