简体   繁体   English

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

[英]Searching for and printing a specific line using Java IO

I have a program designed to function as an address book. 我有一个旨在用作通讯录的程序。 It has 3 methods: One that allows new contacts to be added, one that prints out all the contacts in the book, and one that lets you search for a contact by last name and only print out information on the contact. 它有3种方法:一种允许添加新联系人,一种可以打印出本书中的所有联系人,另一种可以让您按姓氏搜索联系人,并且仅打印出联系人信息。 I have the first two working perfectly, but the last one always prints out all the contacts on the list and I have no idea why. 我的前两个工作正常,但最后一个总是打印出列表中的所有联系人,我也不知道为什么。

The problem is in the search() method. 问题出在search()方法中。 I've added a lot of comments so you guys can tell what's going on in the program. 我添加了很多评论,以便你们可以知道程序中发生了什么。

WARNING: Wall of code incoming. 警告:代码墙进入。

/**
*/
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

And here is the very simple test class that goes with it: 这是它附带的非常简单的测试类:

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); }
      }
   }
}

I found the error. 我发现了错误。 You gotta take away the ";" 您必须拿走“;”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM