【发布时间】:2020-06-20 15:29:19
【问题描述】:
我正在尝试阅读一个简单的书单文本文件,其中书名和作者用“-”分隔。使用扫描仪、文件阅读器和跳过将书名与作者分开并打印。我无法理解输出的程序流程:
import java.io.*;
import java.util.*;
public class FileReaderDemo {
public static void main(String[] args) {
File file = new File("Filepath....>BookList.txt");
Scanner scan = null;
try {
scan = new Scanner(new FileReader(file));
scan.useDelimiter("-");
while(scan.hasNext())
{
System.out.println("Book -> "+scan.next());
scan.skip(scan.delimiter());
System.out.println("Author -> "+scan.next());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scan.close();
}
}
文本文件包含以下内容:
Harry Potter & Order of Phoenix - J K Rowling
Autobiography of a Yogi - Parmahansa Yoganand
Alice in Wonderland - Lewis Carroll
输出如下:
Book -> Harry Potter & Order of Phoenix
Author -> J K Rowling
Autobiography of a Yogi
Book -> Parmahansa Yoganand
Alice in Wonderland
Author -> Lewis Carroll
我无法理解的是,第一本书打印得很好,第二本书的名称如何打印没有“Book->”或前面的任何 println 语句,然后再次打印第三本书,最后是作者最后一部分?
【问题讨论】: