Hi, I'm working on an assignment for programming class where we're supposed to create a method that takes the contents from a text file (one giant string) and stores them piece by piece in a linked list. I'm a little stuck and not sure where to go from here, or if I'm on the right track...

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;

public class LinkedLists
{
    // instance variables - not sure if I should use these?
    // private String file;
    // private LinkedList<String> list;

    /**
     * A method to read the items from a file and convert them to a list.
     * @param fileName the file to be read
     * @return readItems a linked list containing read items.
     */
    public static LinkedList<String> readItems(String fileName) throws FileNotFoundException
    {
        File input = new File(fileName);
        Scanner in = new Scanner(input);
        String file = "";

        // Copy the contents from the file to a String
        while (in.hasNext())
        {
            file = in.next();
        }

        // Create the list
        LinkedList<String> list = new LinkedList<String>();       
        ListIterator<String> iter = list.listIterator();

        // Copy the String contents to the Linked List
        while (iter.hasNext())
        {
            for (int i=0; i<file.length(); i++)
            {
                file = in.next();
                list.add(file);
            }
        }

        return list;
    }
}

There is also a tester class which is supposed to create a linked list from the text file and print the list.

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

public class LinkedListTest
{
    public static void main(String[] args)
    {
        File input1 = new File("input1.txt");
        Scanner in = new Scanner(input1);

        String s = in.next();

        System.out.print(readItems(s));
    }
}

I'm not sure how to implement my readItems method into this main method. Should I convert my text file to a String in the main method too? So confused...

  • I've also posted looking for help.

Dani AI

Generated

You are close, but two things are tripping you up: (1) you never add anything to the list while scanning the file, and (2) in main you pass the first token from the file to readItems instead of the file name itself. Also note that while (iter.hasNext()) on a brand-new list is immediately false, so that loop will never run.

A straightforward approach is to build the list directly as you read. No need to first concatenate the entire file into one giant String, which only wastes memory.

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

public class LinkedLists {
    public static LinkedList<String> readItems(String fileName) throws FileNotFoundException {
        LinkedList<String> list = new LinkedList<>();
        try (Scanner sc = new Scanner(new File(fileName))) {
            sc.useDelimiter("\\s+"); // split on any whitespace
            while (sc.hasNext()) {
                list.add(sc.next());
            }
        }
        return list;
    }
}

And call it like this:

public class LinkedListTest {
    public static void main(String[] args) throws Exception {
        LinkedList<String> items = LinkedLists.readItems("input1.txt");
        System.out.println(items);
    }
}

If your instructor expects you to start from a “giant string”, you can still follow the idea that suggested: read the file once, split on whitespace, then add each token. Prefer \\s+ to avoid empty tokens and handle spaces, tabs, and newlines correctly. Example variation:

String text = new java.util.Scanner(new File(fileName)).useDelimiter("\\Z").next();
for (String word : text.split("\\s+")) {
    list.add(word);
}

Tip: avoid variable names like file for both a String and a File, and always close your Scanner (try-with-resources does that).

you dont have to read the file again on the read method because you already go the input on the main method.
what you can do is store each word of the string into a node of the linked list using a for loop and creating an array of the words.

mystring.split("\s") will retur and array of the words in the string save that into a String array.

then using a for loop add each element of the array to the list.

for(int i = 0; i<StringArray.length; i++)
{
   linkedList.add(StringArray[i]); 
 }

and there you got it :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.