【问题标题】:Searching for and printing a specific line using Java IO使用 Java IO 搜索和打印特定行
【发布时间】:2017-04-18 16:00:36
【问题描述】:

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

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

警告:输入代码墙。

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

这是一个非常简单的测试类:

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

【问题讨论】:

  • 我不知道为什么。我正在运行调试器,字段明显不同,但名称仍然打印。奇怪……你试过运行调试器吗?
  • @Nick Ziebert 是的,我做到了:/ 这实际上是我的一门编程课程的作业,我今天花了 2 个小时和我的助教一起试图找出问题所在。在这一点上,搜索方法中的代码实际上与他的相同,但由于某种原因,我的两个都打印了,而他只打印了一个。

标签: java search text io bufferedreader


【解决方案1】:

我发现了错误。你必须去掉“;”

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

【讨论】:

  • 天哪。两个人看这个东西超过 2 个小时,我们没有注意到这一点。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 2014-05-05
  • 1970-01-01
相关资源
最近更新 更多