我正在尝试创建一个实用工具类,使用 java.util.Scanner
从标准控制台获取输入package dbasics;
import java.util.*;
public class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
return n;
}
public static int[] getNumericArrayInput(int n) {
//System.out.println("Enter "+n+" integers seperated by a whitespace ");
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
在另一个类中调用静态方法时,方法getNumericInput()
正常工作,但以下方法getNumericArrayInput(int n)
会导致异常。
package dbasics;
public class Demo {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
}
运行此结果会导致以下异常
Enter a integer
5
Number 5
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 dbasics.Utils.getNumericArrayInput(Utils.java:21)
at dbasics.Demo.main(Demo.java:9)
我注意到的有趣的事情是,如果我注释掉第一个输入程序,数组输入正常工作
答案 0 :(得分:1)
您正在关闭异常中导致的函数中的Scanner: 试试这个:
import java.util.*;
class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
return n;
}
public static int[] getNumericArrayInput(int n) {
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
public class cn {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
try{
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
有关详细信息,请参阅this link
答案 1 :(得分:0)
在第一种方法中,请勿关闭scanner