Java中创建多个Scanner对象时报错NoSuchElementException

文章部分转自:https://www.cnblogs.com/qingyibusi/p/5812725.html

当在Java中创建多个Scanner对象并运行时会报错:NoSuchElementException,这是为什么呢?看看下面就知道了:

比如我们创建了两个方法A、B,我们在方法A中实现代码如下

        public static void A(){
           Scanner   sc = new Scanner(System.in);
           int     s = sc.nextInt();
           sc.close;
       }
        public static void B(){
         Scanner   sc = new  Scanner(System.in)
         int  s = sc.nextInt();
       }

当先调用方法A时,此时并不会报错,但你调完方法A再去调方法B时便会标错了,报错为原因是因为:当你在方法A里把扫描器Scanner关掉时,扫描器里的输入流(System.in)也一起关掉了,再调方法B时,虽然重新创建了Scanner类的对象,但输入流(System.in)是无法再次打开的,因此会抛出异常NoSuchElementException。

报错的具体原因如下:

1、在 FistTime(){...} 使用sc.close();进行关闭处理,会把System.in也关闭了

2、当下次在SecondTime(){...}方法中再进行new Scanner (System.in)操作读取的时候,因为输入流已经关闭,所以读取的值就是-1;

3、在Scanner 的readinput()方法里面有以下代码:

        try {
             n = source.read(buf);
            } catch (IOException ioe) {
       lastException = ioe;
       n = -1;
        }

        if (n == -1) {
        sourceClosed = true;
        needInput = false;
        }

4、因为读到了-1就设置sourceClosed =true;neepinput=false;

5、在next()方法里面有以下代码:

        if (needInput)
          readInput();
        else
          throwFor();

6、当needinput为false,就执行throwFor,因此再看throwFor

        skipped = false;
        if ((sourceClosed) && (position == buf.limit()))
            throw new NoSuchElementException();
        else
            throw new InputMismatchException();

7、position 是当前读取的内容在缓冲区中位置,因为读取的是-1,因此position =0,而buf.limit()也等于0,因此就执行了throw new NoSuchElementException();

解决方法如下:

可以主类中设计一个 全局静态变量函数: static Scanner sc = new Scanner(System.in); , 然后最后主方法的末尾关掉:sc.close()就行了

原文地址:https://www.cnblogs.com/muyouzhi/p/12578412.html