
-----------------------------------
supahsain08
Thu May 29, 2008 6:01 pm

Need help with transfering names from a txt file to array
-----------------------------------
Hello, my program is suppose to read data from a txt file
txt file has like 20 names (each name on a different line)
For example
Sam
dam
dog
lamb

I am almost done, but i am experiencing problems reading names from a txt file

here's my code so far

import java.io.*;
public class sort
{
    public static void main (String[] args) throws Exception
    {
        FileInputStream File1;
        DataInputStream In;
        String fileInput = "";
        File1 = new FileInputStream ("names.txt");
        In = new DataInputStream (File1);

        while (In.available () > 0)
        {
            fileInput = In.readLine ();
            System.out.println (fileInput);
        }
        System.out.println ("\n\n\n");


         // How do i import names from the txt file here
        String[] names = {"joe", "Slim", "Ed", "george"};
        sort1 (names);
        for (int k = 0 ; k < 4 ; k++)
            System.out.println (names [k]);
    }


    public static void sort1 (String x[])
    {
        int i, j;
        String temp;

        for (i = 0 ; i < x.length - 1 ; i++)
        {
            for (j = i + 1 ; j < x.length ; j++)
            {
                if (x [i].compareToIgnoreCase (x [j]) > 0)
                { // ascending sort
                    temp = x [i];
                    x [i] = x [j];
                    x [j] = temp;

                }
            }
        }
    }
}
 

-----------------------------------
r691175002
Thu May 29, 2008 7:00 pm

Re: Need help with transfering names from a txt file to array
-----------------------------------
Well to start I would suggest switching to a Scanner just to reduce the linecount:
Scanner s = new Scanner(new File("File.txt"));
I believe you are asking how to transfer the names into an array.  IMO the easiest way would be to use an ArrayList:
ArrayList a = new ArrayList();
while (s.hasNext())
    a.add(s.nextLine());
I really don't see any reason not to use the built in classes to do this.  Since it seems that you are learning sorting algorithms, you probbably want a real array so you can use ArrayList.toArray() and have the entire thing read into an array in 5 lines.
