繁体   English   中英

使用多个扫描仪逐行读取文件,从而导致noSuchElementException

[英]Using multiple scanners to read file line by line resulting in noSuchElementException

我不确定何时会收到没有此类元素的异常。 扫描仪似乎无法正确读取我的文件,这似乎是一个问题,但是我不确定我要去哪里。

我正在读取文件,然后使用扫描仪逐行扫描。 但是,当我尝试执行此操作时,会遇到异常行为,例如缺少行或filenotfound异常。

    public static void readMylifeLikeABook(String fileName,int maxItems) {
        // Read file line by line with different elements on each line
        int bookCount=0;
        int movieCount = 0;
        Book [] bookItem =new Book[maxItems];
        Movie [] movieItem =new Movie[maxItems];

        try {
            File file = new File(fileName);
            Scanner scanner = new Scanner(file);
            Scanner line;
            while (scanner.hasNext() && ((bookCount+movieCount)<maxItems)) {
                line = new Scanner(scanner.nextLine()); // scan next line
                if (line.next().contains("Movie")){
                    movieItem[movieCount]= new Movie();
                    movieItem[movieCount].setMediaType("Movie");
                    movieItem[movieCount].setTitle(scanner.nextLine());
                    movieItem[movieCount].setRef(scanner.nextLine());
                    movieItem[movieCount].setPrice(Double.valueOf(scanner.nextLine()));
                    movieItem[movieCount].setDirector(scanner.nextLine());
                    movieItem[movieCount].setActor(scanner.nextLine());
                    System.out.println(movieItem[movieCount].getTitle());
                    movieCount++;
                    line.close();                           // close line
                }
                else if (scanner.next().contains("Book")){
                    bookItem[bookCount]= new Book();
                    bookItem[bookCount].setMediaType("Book");
                    bookItem[bookCount].setTitle(scanner.nextLine());
                    bookItem[bookCount].setRef(scanner.nextLine());
                    bookItem[bookCount].setPrice(Double.valueOf(scanner.nextLine()));
                    bookItem[bookCount].setAuthor(scanner.nextLine());
                    System.out.println(bookItem[bookCount].getTitle());
                    bookCount++;
                    line.close();                           // close line
                }
            }
            scanner.close();
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        //System.out.println(count);
        for (int i=0;i<(bookCount+movieCount);i++) {
            System.out.println(bookItem[i] +"\n\n "+ movieItem[i]);
        }
    }

嗯,是否可以提供正在读取的文件? 这很可能是该文件的一个问题,就像Scanner对象没有要读取的下一行一样,它将引发异常。 确保文件具有所需的行数。

您在构造line之后立即调用line.next() 您需要这样做吗? 如果是这样,也许您首先需要调用hasNext()以确保那里有一个令牌。

(我很确定line.next()如果没有令牌,则抛出NoSuchElementException 。)

另外,对照文件格式检查代码。 文件中是否有空行?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM