有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类(Java)从文本文件加载到Arraylist

对于这个程序,我需要将一本书(标题、作者、价格)的数据列表从文本文件读入一个单独类(书)中的arraylist。 老实说,我只是在Java中使用类作为对象,这是我无法理解的事情之一,而且我对ArrayList没有太多经验

public void loadBook(String fn) throws IOException{     
    ArrayList<Book> books = new ArrayList<Book>();
    Scanner infile = new Scanner(new InputStreamReader (new FileInputStream(fn)));
    int num = infile.nextInt();
    infile.nextLine();
    for (int i=0; i<num; i++) {
        String name = infile.nextLine();
        String author = infile.nextLine();
        Double price = infile.nextDouble();
        Book c = new Book (name, author, price);
        books.add(c);
    }
    infile.close();
    }

这是Book类中当前的代码

public class Book extends Model {

public Book(String name, String author, Double price) {
    String Name = name;
    String Author = author;
    Double Price = price;
}   

文件“fn”包含以下内容:

3
名称
作者
10点

但loadBook在读取文件时仍会引发错误:@

任何帮助都将不胜感激,谢谢


共 (2) 个答案

  1. # 1 楼答案

    试一试 确保您的文本文件在eclipse中的包中。txt扩展

    //see what your default path is
    System.out.println(System.getProperty("user.dir"));
    
    //then use this code as continuation to the default path...for example if your path leads to your working directory
    Scanner in = new Scanner(new FileInputStream("src/package_name/filename.txt"));
    
  2. # 2 楼答案

    通过此输入:

    3
    name
    author
    10.00
    

    此代码

    int num = infile.nextInt();
    infile.nextLine();
    for (int i=0; i<num; i++) {
        String name = infile.nextLine();
        String author = infile.nextLine();
        Double price = infile.nextDouble();
        Book c = new Book (name, author, price);
        books.add(c);
     }
    

    num设置为3,因此执行for循环3次。在每次迭代中,方法nextLine()被调用两次,方法nextDouble()被调用一次。但是文件中只剩下3行,所以您太频繁地调用nextLine()。尝试将您的输入更改为

    1      <  number of listed books, not lines.
    name
    author
    10.00