NoSuchElementException in Scanner

眉间皱痕 提交于 2019-12-13 21:22:05

问题


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.

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.

Problem occurs at 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;

回答1:


The culprit is:

while((line = scanner.next()) != null)

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.
}



回答2:


Scanner.next throws a NoSuchElement exception if there are no more tokens.

I see that you are iterating through a list of files. Is it possible that the first file you get in that list is empty?

Can you print out the name of the file and check to confirm?



来源:https://stackoverflow.com/questions/13963240/nosuchelementexception-in-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!