Question

I have this program that reads a text file from my computer. the text file is a list of titles. Im trying to figure out how to tokenize what is returned so that I get the full name instead of a piece. All the examples I am able to find involve regular arrays and Im using an arraylist. I need to be able to read each string back into my arraylist and cut it off where the & are.

The Text file looks like this:

Star Wars& DVD&

Lord of the Rings& DVD&

Resident Evil& DVD&

public static void main(String[] args) {

        File f = new File("file.txt");
        try {
            ArrayList<String> lines = get_arraylist_from_file(f);
            for (int x = 0; x < lines.size(); x++) {
                System.out.println(lines.get(x));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("done");

    }

    public static ArrayList<String> get_arraylist_from_file(File f)
            throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }
Was it helpful?

Solution

     public static ArrayList<String> get_arraylist_from_file(File f) throws FileNotFoundException {
        Scanner scanner;
        ArrayList<String> list = new ArrayList<String>();
        scanner = new Scanner(f);
        String s = scanner.nextLine();

        while(scanner.hasNextLine()){
        String[] tempList = s.split("&"); //This will give you this [title][ DVD]
        String title = tempList[0];
        String type = tempList[1].subString(1); //If you want the input at the place of DVD, with the space removed
        list.add(title);
        s = scanner.nextLine();
        }
        scanner.close();
        return list;
}

OTHER TIPS

while (s.hasNextLine()) {
    list.add(s.nextLine().replaceAll("&", ""));
}

removes the ampersands

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top