【发布时间】:2016-10-11 18:52:12
【问题描述】:
我一直在做作业,但遇到了问题。我的代码从 txt 文件中扫描有关书籍的一些信息(作者、标题等),然后打印出来。首先我尝试打印作者、标题、ISBN 代码、页数,然后是 15*页数的书籍价格。到目前为止它有效,但是我想为每本书添加一个数字,所以它就像一个列表。但是当我修改代码以添加这些数字时,代码不想扫描它们。它说
int不能转成String
出于好奇,我尝试将数字扫描为字符串,但随后错误消息显示
字符串不能转换为int
我的书课:
public class Book {
private int number;
private String author;
private String title;
private String code;
private int pages;
private static int multiplier = 15;
public Book(String author, String title, String code, int pages, int number) {
this.number = number;
this.author = author;
this.title = title;
this.code = code;
this.pages = pages;
}
@Override
public String toString() {
return author + " - " + title + ", ISBN:" + code + ", " + pages + " pages, Price: " + price() + "Ft";
}
public int price() {
return multiplier * pages;
}
public static int getMultiplier() {
return multiplier;
}
public static void setMultiplier(int multiplier) {
Book.multiplier = multiplier;
}
public int getNumber() {
return number;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getCode() {
return code;
}
public int getPages() {
return pages;
}
}
还有我的“控制器”类:
public class Controller {
void start() {
scanning();
printing("Avilable books: ");
}
private List<Book> books = new ArrayList<>();
private void scanning() {
try {
Scanner fajlScanner = new Scanner(new File("books.txt"));
String row;
String data[];
while (fajlScanner.hasNextLine()) {
row = fajlScanner.nextLine();
data = row.split(";");
//1;J.K. Rowling;Harry Potter and the Philosopher's Stone;1782637594826;342
//this line below gives the error for the data[0]
books.add(new Book(Integer.parseInt(data[0]), data[1], data[2], data[3], Integer.parseInt(data[4])));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printing(String title) {
System.out.println(title);
for (Book book : books) {
System.out.println(book);
}
}
}
我的txt内容:
1;J.K. Rowling;Harry Potter and the Philosopher's Stone;1782637594826;342
2;J.R.R. Tolkien;The Fellowship of the Ring;1827493762573;431
3;Stephen King;Needful Things;8274653821647;411
4;Eric Knight;Lassie Come-Home;7263845618293;138
5;Molnár Ferenc;A pál utcai fiúk;9283746192846;194
6;Winston Groom;Forrest Gump;0385231342;228
7;Antoine de Saint-Exupéry;The Little Prince;8362748172649;69
8;Stephen King;Cujo;2918467382914;362
我可以很好地扫描页面,但是“数字”有问题。
【问题讨论】:
-
没有books.txt怎么办?为什么不打印出每个数组的内容 before 解析来自己测试变量?或者使用调试器。
-
您似乎试图以错误的顺序传递参数。
-
考虑将每个解析放在自己的一行上——以使调试更容易。在解析之前打印出每个字符串。在解析之前检查这些行不需要
trim()'ed。