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

Username:   Password: 
 RegisterRegister   
 How do i read a file?
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
B-747




PostPosted: Thu Mar 31, 2005 7:56 pm   Post subject: How do i read a file?

This program is suppose to read the names from a file and then output wether the name enetered by the user exists in the file! There are a bunch of names in the file name "name.txt"! Can someone plz fix this program for me!


// The "Program1" class.
import java.awt.*;
import hsa.Console;

public class Program1
{
static Console c; // The output console

public static void main (String[] args)
{
c = new Console ();
String name, name2;
c.println("Enter a name fromt he file:");
name=c.readString();
name2="name.txt";
BufferedReader name3;
name3=new BufferedReader(new FileReader(name2));

// Place your program here. 'c' is the output console
} // main method
} // Program1 class
Sponsor
Sponsor
Sponsor
sponsor
1of42




PostPosted: Fri Apr 01, 2005 5:06 pm   Post subject: (No subject)

what's to fix? assuming there is one name per line in the file, simply call the readLine method on the bufferedReader, trim it, and test for its equality with the name given to you. have a boolean initialized to false
code:

import java.io.*;
public class FindName
{
    public static boolean nameExists (String file, String name) throws IOException
    {
        BufferedReader reader = new BufferedReader (new FileReader (file));
        String temp;

        while ((temp = reader.readLine ()) != null)
        {
            temp = temp.trim ();
            if (temp.equals (name))
                return true;
        }
        return false;
    }


    public static void main (String[] args) throws IOException
    {
        BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
        String file, name;
        boolean nameExists;

        System.out.println ("Enter a name from the file:");
        name = reader.readLine ().trim ();
        System.out.println ("Enter the file to be read");
        file = reader.readLine ().trim ();

        nameExists = nameExists (file, name);

        System.out.println (nameExists);
    }
}


This works. You'll have to change it to use the Console class yourself, because I refuse on principle to use that thing.
B-747




PostPosted: Sun Apr 03, 2005 3:39 pm   Post subject: (No subject)

Thanks "1of42". I appreciate ur help!
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  [ 3 Posts ]
Jump to:   


Style:  
Search: