使用 Java IO 搜索并打印特定行

Searching for and printing a specific line using Java IO

我有一个旨在用作地址簿的程序。它有 3 种方法:一种允许添加新联系人,一种打印出联系人簿中的所有联系人,还有一种允许您按姓氏搜索联系人并只打印出联系人的信息。前两个我工作得很好,但最后一个总是打印出列表中的所有联系人,我不知道为什么。

问题出在 search() 方法中。我已经添加了很多评论,所以你们可以知道程序中发生了什么。

警告:代码墙传入。

/**
*/
import java.util.*;
import java.io.*;

public class ContactList
{
   /**
   Contact list file name 
   */
   private String filename;   

   /**
   ContactList constructor accepts a String parameter
   */
   public ContactList(String inFileName)
   {
      filename = inFileName;
   }

   /**
      3) add a new record to the file. Open the file for writing in append mode.
         a) prompt the user to enter data for each field in the record. Each field is a String.
            The last name is required. If the last name is the empty string(""), return to the menu.
         b) when the user has completed entering data(i.e., all the fields have been prompted), re-display the user choices
         c) do not overwrite existing data
   */
   public void new_record()
   {      
      /*
      Prompt for data:
         Last name
         First name
         Phone

    */
      //Craete a scanner object
      Scanner in = new Scanner(System.in);


      //prompt for the last name
      System.out.println("Please Enter Contact's Last Name: ");

      //input the last name
      String lastName = in.nextLine();

      //the Last_name must not be empty
      if(lastName.length() > 0 )
      {
          //get the first name and the phone
          System.out.println("Please Enter Contact's First Name: ");
          String firstName = in.nextLine();

          System.out.println("Please Enter Contact's Phone Number [xxx-xxx-xxxx]: ");
          String phone =  in.nextLine();

          //create the output string
          String contact = lastName + ",";
          contact = contact + firstName + ",";
          contact = contact + phone;

          System.out.println("");
          System.out.println("Last Name: " + lastName);
          System.out.println("First Name: " + firstName);
          System.out.println("Phone: " + phone); 
          System.out.println("");        

          //try to open the file for writing - append the data
          FileWriter fw = null;
          BufferedWriter bw = null;         
          try
          {            
              fw = new FileWriter(filename,true);
              bw = new BufferedWriter(fw);
          }
          catch(IOException ioe)
          {
              System.out.println("new_record: Exception opening the file for writing");
          }
          //try to wrtie the data
          try
          {
              bw.write(contact);
              bw.newLine();       
          }
          catch(IOException ioe)
          {
              System.out.println("new_record: Exception writing to the file");
          }
          //try to close the file
          try
          {
              bw.flush();
              bw.close();
              fw.close();
          }
          catch(IOException ioe)
          {
              System.out.println("new_record: Exception closing the file");
          }

      }//end of test of Last_name

   }//end of new_record

    /**
    2) display all last names and first names in the file. 
       Open the file for reading, read each record and 
       display the field values.
      a) display all the lastName, firstName paired fields in the file; 
         display with the format lastName, firstName
      b) when all records have been displayed, display the record count  - the record count is the number of records read and should equal the number of records in the file
      c) after all the records and the count have been displayed, display the user choices

    */
    public void display_names()
    { 
        FileReader fn = null;
        BufferedReader br = null;

        //try to open the file for reading
        try
        {
            fn = new FileReader(filename);
            br = new BufferedReader(fn);
        }
        catch(IOException ioe)
        {
            System.out.println("display_names: Exception opening the file");
        }

        /*
        try to read each record and display the field values.
        a) display all the lastName, firstName paired fields in the file; 
           display with the format lastName, firstName
           count each record that is read 
        */
        int counter = 0; //record counter
        try
        {   
            //read the first record
            String line = br.readLine();
            //while the record is not null, display the record, count the record
            while(line != null)
            {
                System.out.println(line);
                counter++;
                line = br.readLine();
            }       
        }
        catch(IOException ioe)
        {
            System.out.println("display_names: Exception reading the file");
        } 

        //try to close the file
        try
        {
            br.close();   
            fn.close();     
        }
        catch(IOException ioe)
        {
            System.out.println("display_names: Exception closing the file");
        }
        //display a count of the records read
        System.out.println("");
        System.out.println("Records Displayed: " + counter);
        System.out.println("");
    }//end of display_names

    /**
      1) search an address file for a particular last name 
      and then display the Last name, the first name, and 
      the phone for each match
      2) display the count of records which match the last name

   */
    public void search(String findMe)
    {
        FileReader fn = null;
        BufferedReader br = null;

        //try to open the file for reading
        try
        {
            fn = new FileReader(filename);
            br = new BufferedReader(fn); 
        }
        catch(IOException ioe)
        {
            System.out.println("search: Exception opening the file");
        }

        //try to read each record
        int counter = 0;
        try
        {
            String line = br.readLine();   
            while(line != null)
            {
                String [] fields = line.split(",");
                if(findMe.equals(fields[0]));
                {
                    System.out.println(line);
                    System.out.println("");
                    counter++;
                }
                line = br.readLine();
            }      
        }
        catch(IOException ioe)
        {
            System.out.println("Search: Exception Reading the File.");
        } 

        //Try to close the file
        try
        {
            br.close();
            fn.close();      
        }                   
        catch(IOException ioe)
        {
            System.out.println("search: Exception closing the file");
        }
        //dislay a count of the records found 
        System.out.println("Records Searched: " + counter);
        System.out.println("");     
    }//end of search
}//end of class

下面是非常简单的测试 class:

import java.util.*;
public class TestContactList
{
    public static void main(String [] args)
    {
        final int ONE   = 1;
        final int TWO   = 2;
        final int THREE = 3;
        final int FOUR  = 4;
        final int FIVE  = 5;

        Scanner scan = new Scanner(System.in);
        while(true)
        {
            System.out.println("1) Search the file for a last name ");
            System.out.println("2) Display all last & first names in file");
            System.out.println("3) Add a new record to the file ");
            System.out.println("4) End the program ");
            System.out.print("Please choose 1 - 4: ");
            int choice = scan.nextInt();
            scan.nextLine();

            /*
            Create a new ContactList object with the name of the
            contact list file.
            */
            ContactList cl = new ContactList("MyAddressBook.txt");

            if(choice == ONE)
            {
                System.out.print("Enter name to find: ");
                String findMe = scan.nextLine();
                cl.search(findMe);
            }

            if(choice == TWO)
            {   
                // then call display names
                cl.display_names();
            }

            if(choice == THREE)
            { 
                // then call new record 
                cl.new_record();
            }

            if(choice == FOUR)  { System.exit(0); }
      }
   }
}

我发现了错误。你得拿走“;”

if(findMe.equals(fields[0])); <---oops