简体   繁体   中英

I am looking for the code to successfully store the information read from my input file into an ArrayList in Java

This is what I have tried so far... I have a method inside of this package in a separate class called loadData(String) that loads the data inside an input file. However this use of the loadData method gives an error saying this type is undefined for LibraryApplication.

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileNotFoundException;

public class LibraryApplication {

    public static void main(String[] args) throws FileNotFoundException{
            try {
                Scanner x = new Scanner(new File("BookCatalog.txt"));
                ArrayList<Book> booklist = new ArrayList<Book>();
                loadData()
            } 
            catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    
        }    
    }

    public void loadData(String filename) {

        this.filename = filename;

        Scanner reader = null;
        try {
            reader = new Scanner(new File(filename));
            Book book = null;

            while (reader.hasNextLine()) {
                book = new Book(reader.nextLine(), reader.nextLine(), reader.nextLine(), reader.nextLine(),
                        Integer.parseInt(reader.nextLine()));
                reader.next();
                booklist.add(book);
            }
            booklist.sort(null);
            reader.close();
        } catch (IOException e) {
            System.out.print("Error: Unable to load file. ");
        }
    }
}

Class LibraryApplication has no method named loadData(). You probably need to implement it.

Furthermore, your loadData -- where is it going to get the data, and where is it going to put it?

Let's say you have this:

public class Loader {
    public void loadData(Scanner x, ArrayList<Book> books) {
        ...
    }
}

Then in main, you need to do:

Loader loader;
loader.loadData(s, booklist);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM