我正在开发一种解析器(爱好项目),它接受一个Cpp文件,读取文件中的注释,然后尝试根据它创建一个头文件。
我面临的问题是java.util.Scanner
即将阅读第一行。程序停止并给我NoSuchElementException
。我无法弄清楚应该出错的是什么。我检查了路径和路径名都是正确的。该文件必须在那里,我可以在调试时读取Scanner对象上的字段。那究竟是什么问题?
有些人暗示它可能认为文件中没有行。
问题发生在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;
答案 0 :(得分:2)
罪魁祸首是:
while((line = scanner.next()) != null)
scanner.next()
will throw a NoSuchElementException
if there are no more tokens available。您可以改为使用hasNext
方法:
while(scanner.hasNext()) {
String line = scanner.next();
//etc.
}
答案 1 :(得分:0)