Java学习笔记之Scanner报错java.util.NoSuchElementException

转载自:IT学习者-螃蟹java

 

一个方法A使用了Scanner,在里面把它关闭了。而后又在方法B里调用方法A以后就不能再用Scanner了Scanner in = new Scanner(System.in);学习

测试代码以下:测试

import java.util.Scanner; 
/** 
* 
* @author IT学习者-螃蟹 
* 
* 
*/ 
public class ItxxzScanner { 
//第一次输入 
public void FistTime (){ 
Scanner sc = new Scanner (System.in); 
int first = sc.nextInt(); 
System.out.println("first:"+first); 
sc.close(); 
} 
//第二次输入 
public void SecondTime(){ 
Scanner sc = new Scanner (System.in); 
int second = sc.nextInt(); 
System.out.println("second:"+second); 
sc.close(); 
} 
//测试入口 
public static void main(String arg[]){ 
ItxxzScanner t = new ItxxzScanner(); 
t.FistTime(); 
t.SecondTime(); 
} 
} 

 


运行后便抛出以下异常:spa

 

 

能够看出,在代码第29行的时候报错,抛出了 java.util.NoSuchElementException 异常,code

下面咱们来分析一下报错的缘由:blog



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

二、当下次在SecondTime(){...}方法中再进行new Scanner (System.in)操做读取的时候,由于输入流已经关闭,因此读取的值就是-1; input

三、在Scanner 的readinput方法里面有如下代码:it

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

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

 



四、由于读到了-1就设置sourceClosed =true;neepinput=false;io

五、在next方法里面有如下代码:

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

 



六、当needinput为false,就执行throwFor,所以再看throwFor

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

 

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

相关文章
相关标签/搜索