Scanner sc = new Scanner(System.in).useDelimiter("\\s");
int a[] = new int[50];
int i = 0;
while (sc.hasNextInt()) {
a[i++] = sc.nextInt();
}
sc.close();
Scanner sc2 = new Scanner(System.in);
System.out.println("请输入一个小于" + i + "的数");
int m = sc2.nextInt();
sc2.close();
上面这么写就会报java.util.NoSuchElementException异常:
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)
原因是我们在上面关了System关闭,即对于系统文件关闭了无法再打开,所以就报错了。改的方法很简单,两个Scanner放到最后一块关闭就是了:
Scanner sc = new Scanner(System.in).useDelimiter("\\s");
int a[] = new int[50];
int i = 0;
while (sc.hasNextInt()) {
a[i++] = sc.nextInt();
}
Scanner sc2 = new Scanner(System.in);
System.out.println("请输入一个小于" + i + "的数");
int m = sc2.nextInt();
sc.close();
sc2.close();
这样该报错就解决了!
注:以上文章仅是个人学习过程总结,若有不当之处,望不吝赐教。