扫描仪中的NoSuchElementException [英] NoSuchElementException in Scanner
问题描述
我正在研究一种解析器(业余项目),它需要一个Cpp文件,读取文件中的注释,然后尝试基于该文件创建头文件.
I am working on a kind-of parser (hobby project) which takes a Cpp file, reads through the comments in the file, and then tries to create a header file based on that.
我面临的问题是java.util.Scanner
即将读取第一行时.程序停止并给我NoSuchElementException
.我真的不知道应该怎么做.我检查了路径和路径名是否正确.该文件必须在此处,并且在调试时也可以读取Scanner对象上的字段.那到底是什么问题呢?
The problem I am facing is when the java.util.Scanner
is about to read the very first line. The program stops and gives me the NoSuchElementException
. I can't really figure out what should be wrong. I checked that both path and pathname are made correctly. The file must be there, and I can read fields on the Scanner object as well when I debug. So what's the problem exactly?
有人暗示它可能认为文件中没有行.
Some was hinting at that it might think there are no lines in the file.
问题出现在while((line = scanner.next()) != null) {
@Override
public void run() {
Scanner scanner = null;
String filename = "", path = "";
StringBuilder puBuilder, prBuilder, viBuilder;
puBuilder = new StringBuilder();
prBuilder = new StringBuilder();
viBuilder = new StringBuilder();
for(File f : files) {
try {
filename = f.getName();
path = f.getAbsolutePath();
path = path.replace(filename, "");
filename = filename.replace(".cpp", "");
scanner = new Scanner(new FileReader(f));
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " + ex.getMessage());
}
String line;
String tag;
while((line = scanner.next()) != null) {
line = line.trim();
if(line.startsWith(PUBLIC)) {
tag = PUBLIC;
推荐答案
罪魁祸首是:
while((line = scanner.next()) != null)
scanner.next()
将如果没有更多可用令牌,则抛出NoSuchElementException
.您可以改用hasNext
方法:
scanner.next()
will throw a NoSuchElementException
if there are no more tokens available. You could use the hasNext
method instead:
while(scanner.hasNext()) {
String line = scanner.next();
//etc.
}
这篇关于扫描仪中的NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!