Java Scanner NoSuchElementException
今天同学问我一个Java问题,代码结构如下:
Scanner scan = new Scanner(System.in);
scan.next();
scan.close();
scan = new Scanner(System.in);
scan.next();
当程序运行到第五行是会抛出java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
于是按照错误栈的轨迹查找原因。
简要的说,就是前后两次实例化的参数System.in是用一个对象,是InputStreamReader对象,每个该对象包含一个
StreamDecoder 实例 sd
private final StreamDecoder sd;
而scan.close()方法为
public void close() {
if (closed)
return;
if (source instanceof Closeable) {
try {
((Closeable)source).close();
} catch (IOException ioe) {
lastException = ioe;
}
}
sourceClosed = true;
source = null;
closed = true;
}
当执行到 ((Closeable)source).close();就会进入InputStreamReader的close()方法:
public void close() throws IOException {
sd.close();
}
这里的sd就是上面提到的InputStreamReader对象,(有查了StreamDecoder 源代码,但没更深入下去),此时sd已关闭。
当执行如错误产生代码的第5行代码 scan.next()时,
public String next() {
ensureOpen();
clearCaches();
while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid <mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js" mce_src="http://hi.images.csdn.net/js/blog/tiny_mce/themes/advanced/langs/zh.js"></mce:script><mce:script type="text/javascript" src="http://hi.images.csdn.net/js/blog/tiny_mce/plugins/syntaxhl/lan
相关文档:
目前JAVA2有三个版本:J2EE(企业版)、J2SE(标准版)、J2ME(微型版)
1、J2SE(JAVA2 Standart Edition)
JAVA2标准版 支持所有JAVA标准规范中所定义的核心类函数库和所有的JAVA基本类别。J2SE定位在客户端程序的应用上。
2、J2EE(JAVA2 Enterprise Edition)
......
package test;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class XmlTest {
public static void main(String[] args) {
File xmlFile=new File("test/xml.xml");
DocumentBuilderFactory documentBuilderFactor ......
import java.awt.Color;
import java.io.FileOutputStream;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lo ......
13.2.1 网络编程步骤
按照前面的基础知识介绍,无论使用TCP方式还是UDP方式进行网络通讯,网络编程都是由客户端和服务器端组成。当然,B/S结构的编程中只需要实现服务器端即可。所以,下面介绍网络编程的步骤时,均以C/S结构为基础进行介绍。
......