我一直在做我的功课,但我遇到了一个问题。我的代码从txt文件扫描一些关于书籍(作者,标题等)的信息,然后打印出来。首先,我尝试打印作者,标题,ISBN编码,页数,然后是15 *页数的书籍价格。它到目前为止,但我想为每本书添加一个数字,所以它就像一个列表。但是当我修改代码来添加这些数字时,代码不想扫描它们。它说Java - 一个parseInt显示错误,另一个不是
INT不能转换为字符串
我试图扫描数字作为字符串是出于好奇,但随后的错误消息说,
字符串不能转换到诠释
的My Book等级:
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?为什么不在**解析之前打印出每个数组**的内容**以便为自己测试变量?或者使用调试器。 –
你似乎试图以错误的顺序传递参数。 – user2357112
考虑将每个解析放在它自己的一行上 - 以便于调试。在解析之前打印出每个字符串。检查在分析之前,行不需要“trim()”。 –