0

このプログラムでは、書籍のデータのリスト (タイトル、著者、価格) をテキスト ファイルから別のクラス (書籍) の配列リストに読み込む必要があります。正直なところ、Java 内でクラスをオブジェクトとして使用することは、私が理解できないことの 1 つにすぎず、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.00

しかし、 loadBook はファイルを読み込むときにまだエラーをスローします:@

どんな助けでも大歓迎です、ありがとう!!

4

2 に答える 2

3

この入力で:

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

3に設定さnumれるため、forループを3回実行します。各反復で、メソッドnextLine()は2回と1回呼び出されnextDouble()ます。ただし、ファイルにはあと3行しかないため、nextLine()頻繁に呼び出しています。入力をに変更してみてください

1      <-- number of listed books, not lines.
name
author
10.00
于 2013-02-13T16:08:41.277 に答える
1

テキスト ファイルが .txt 拡張子の Eclipse のパッケージに含まれていることを確認してください。

//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"));
于 2013-02-13T16:09:35.077 に答える