I am trying to read in from a .dat file, which includes a list of names a line of asterisks and a list of numbers, JUST the names in the file into nodes to be used in a linked list. All of the names will be before the line of asterisks. I am using Scanner to read in from the file. How exactly should I read in the names and use them in the Node class?

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

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("lab2.dat"));

                int size = 0;

                Node first = new Node(null, null);
                LinkedList survive = new LinkedList(first, size);

                    while(input.hasNext()){

                       //???

                    }//end while

                    System.out.println(size);

    }//end main
}//end Main class

public class Node {
    private String name;
    private Node next;


    Node(){
        immunity = false;
    }

    Node(String d, Node n){
        name = d;
        next = n;

    }

    public void setName(String d){
        name = d;
    }

    public String getName(){
        return name;
    }

    public void setNext(Node n){
        next = n;
    }

    public Node getNext(){
        return next;
    }  

}//end Node Class

If, persay, you have only 3 lines in your file:

Jim,Gordon,Alex,Cross,Mr. Etc
*****************************
112,1114,111116,123,1342

and your names are split by some regex syntax, you could read the entire line, and than split it by the regex, thus getting all the names. I gave a simple example, for a csv file, but you could extend it to more than that.

Edited 3 Years Ago by Lucaci Andrew

Ok, so I understand how to do that, but let's say that the names are on separate lines from each other? i.e.
Jim
Gordon
Alex
Cross
Mr.
Etc
*************
123
4325
4562
23188
Would it be the same concept? And what would be the best way to accomplish this?

Well, you could parse the lines till you get to the ********* part, like this:

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("lab2.dat"));
    String line;
    while(input.hasNext() &&  (line = input.nextLine()).charAt(0) != '*'){  
        System.out.println(line);
    }
}
This article has been dead for over six months. Start a new discussion instead.