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

问题描述 投票:0回答:1

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

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;
        }

文本文件:

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

错误:类型不匹配:无法从int转换为Patron类型不匹配:无法从int转换为Book

java string-parsing
1个回答
0
投票

要做您想做的事情,需要为BookPatron创建一个构造函数

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

然后您这样称呼它

Book book = new Book(Integer.parseInt(properties[1]));
© www.soinside.com 2019 - 2024. All rights reserved.