Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Need help with transfering names from a txt file to array
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
supahsain08




PostPosted: Thu May 29, 2008 6:01 pm   Post subject: 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)
code:
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

code:
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;

                }
            }
        }
    }
}
Sponsor
Sponsor
Sponsor
sponsor
r691175002




PostPosted: Thu May 29, 2008 7:00 pm   Post subject: 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:
code:
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:
code:
ArrayList<String> a = new ArrayList<String>();
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.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: