我有几个类设计用于模拟图书目录。我有一个Book类(isbn、title等),一个BookNode类,一个BookCatalog类,其是一个书籍的LinkedList和一个驱动程序类(gui)。我的问题在于,我在BookCatalog中使用了toString()方法,它应该返回所有书籍的字符串表示形式。Book类还覆盖了toString()。我需要让每个书籍字段都由“制表符”分隔,每个书籍都由“新行”分隔。当我尝试将书籍目录使用PrintStream打印到.txt文件时,\n无法被识别。
我尝试将它更改为System.getProperty(line.separator),这样可以正确显示bookcatalog。但现在我有一个问题,Scanner无法正确读取文件,并抛出“NoSuchElementException”。我如何使scanner忽略line.separator或使printStream使用\n?
Book.java
我尝试将它更改为System.getProperty(line.separator),这样可以正确显示bookcatalog。但现在我有一个问题,Scanner无法正确读取文件,并抛出“NoSuchElementException”。我如何使scanner忽略line.separator或使printStream使用\n?
Book.java
public String toString(){
return isbn+"\t"+lastName+"\t"+firstName+"\t"+title+"\t"+year+"\t"+
String.format("%.2f",price);
BookCatalog.java
public String toString() {
BookNode current = front;
String s="";
System.out.println(s);
while (current!=null){
//each book is listed on separate line
s+=current.getData().toString()+"\n ";//System.getProperty("line.separator")
current = current.getNext();
}
return s;
}
Driver.java
public void loadDirectory() throws FileNotFoundException {
if (f.exists()){
Scanner input = new Scanner(f);
while (input.hasNextLine()){
String bookLine = input.nextLine();
processBookLine(bookLine);
}
}
}
public void processBookLine(String line){
Scanner input = new Scanner(line);
String isbn = input.next();
String lastName = input.next();
String firstName = input.next();
String title = input.next();
while (input.hasNext() && !input.hasNextInt()){//while next token is not an integer
title += " "+input.next();
}
int year = input.nextInt();
double price = input.nextDouble();
Book book = Book.createBook(isbn, lastName, firstName, title, year, price);
if (book!=null){
catalog.add(book);
}
}
PrintStream
抑制了\r
,那么你是错的。你问题的其余部分不够清晰。 - user207421