gpt4 book ai didi

Java - 将非原始数据类型文本文件的字符串解析为整数

转载 作者:行者123 更新时间:2023-12-01 19:06:33 24 4
gpt4 key购买 nike

我试图将文本文件中的字符串转换为非原始数据类型作为整数,但当我尝试解析整数时出现错误

try (Scanner sc = new Scanner(new File(RESOURCE))) {
int line_idx = 1;
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] properties = line.split(SEPARATOR, -1);
try {
Patron patron = Integer.parseInt(properties[0]);
Book book = Integer.parseInt(properties[1]);
LocalDate startDate = LocalDate.parse(properties[2]);
LocalDate dueDate = LocalDate.parse(properties[3]);
Loan loan = new Loan(patron, book, startDate, dueDate);
Book.setLoan(loan);
Patron.addBook(book);
} catch (NumberFormatException ex) {
throw new LibraryException("Unable to parse patron id "
+ properties[0] + " on line " + line_idx + "\nError: " + ex);
}
line_idx++;
}
}

//Loan file
private Patron patron;
private Book book;
private LocalDate startDate;
private LocalDate dueDate;

public Loan(Patron patron, Book book, LocalDate startDate, LocalDate dueDate) {
this.patron = patron;
this.book = book;
this.startDate = startDate;
this.dueDate = dueDate;
}

public Book(int id, String title, String author, String publicationYear, String publisher) {
this.id = id;
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
this.publisher = publisher;
}

文本文件:

3::23::2019-09-23::2019-09-30::

错误:

Type mismatch: cannot convert from int to Patron Type mismatch: cannot convert from int to Book

最佳答案

要完成您想要做的事情,您需要为 BookPatron 制作一个构造函数

public class Book{
public Book(int i){
//what to do whith the int
}
}

然后你就这样调用它

Book book = new Book(Integer.parseInt(properties[1]));

关于Java - 将非原始数据类型文本文件的字符串解析为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com