我有几个类旨在模拟图书目录。我有一个书籍类(isbn、书名等)、一个 BookNode 类、一个 BookCatalog(它是书籍的 LinkedList)和一个驱动程序类(gui)。 我的问题是我在 BookCatalog 中有一个 toString() 方法,它应该返回所有书籍的字符串表示形式。 Book 类还覆盖了 toString()。我应该让书中的每个字段都用“制表符”分隔,每本书都用“换行符”分隔。当我尝试使用 PrintStream 将图书目录打印到 .txt 文件时,\n 没有注册。
我已尝试将其更改为 System.getProperty(line.separator) 以正确显示图书目录。但是现在,我遇到了扫描仪无法正确读取文件并抛出“NoSuchElementException”的问题。如何让扫描仪 1) 忽略 line.separator 或 2) 使用 printStream\n?
书.java
public String toString(){
return isbn+"\t"+lastName+"\t"+firstName+"\t"+title+"\t"+year+"\t"+
String.format("%.2f",price);
图书目录.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;
}
驱动.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);
}
}
最佳答案
换行符 \n
在某些操作系统中不是行分隔符(例如 Windows,它是“\r\n”)——我的建议是您使用 \r\n
而不是,那么它都会看到只有 \n
和 \r\n
的换行符,我从来没有使用过任何问题
此外,您应该考虑使用 StringBuilder
而不是在 BookCatalog.toString()
的 while 循环中连接 String
,它更有效。例如:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
关于java - 如何在字符串中插入换行符到 PrintStream 然后使用扫描仪重新读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15512190/