Question

So i have a tiny problem, for some reason I'm blanking and I've tried moving it inside the loop and back to the outside of the loop it doesn't work. In option two which returns method display_names it reads them from the file it writes them to the console on one line instead of two separate lines.

ex:

Enter two knew people clicking 3:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Display names by clicking 2:
smith, rob, 123-123-1234smith, tom, 123-123-1235

instead of:
smith, rob, 123-123-1234
smith, tom, 123-123-1235

Main Code:

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

public class ContactList
{

  /**
  Contact list file name 
  */
  private String filename;
  String findMe;



   /**
   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(there is a FileWriter constructor with the appropriate parameters).
         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

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

  //prompt for the last name
  System.out.println("Last Name: ");

  //input the last name
  String lastName = scan.next();

  //the Last_name must not be empty
   if(lastName.length() > 0)
   {
     //get the first name and the phone
      System.out.println("Enter First Name: ");
      String firstName = scan.next();
      System.out.println("Enter phone number(xxx-xxx-xxxx): ");
      String phone = scan.next();

      //create the output string

      String info = String.format("%s, %s, %s", lastName, firstName, phone);



      //Declare variables to hold file types
      File file = new File(filename);

      //try to open the file for writing - append the data
      try
      {
          if(!file.exists()){
              PrintWriter out = new PrintWriter(filename);
              out.println(info);
              out.flush();
              out.close();
          }
          else if(file.exists()){
             FileWriter fw = new FileWriter(filename, true);
             fw.write(info);
             fw.close();
          }
      }
      catch(IOException ioe)
      {
        System.out.println("new_record: Exception opening the file for writing");
      }

   }//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()
{
  //delare variables to hold file types
  File file = new File(filename);      



  //try to open the file for reading
  try
  {
     if(file.exists()){ //if the file exists allow it to be read
        BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
        String line = br.readLine();
        int count = 0;
        System.out.println("");
        while(line != null){
            System.out.println(line);
            line = br.readLine();
            count++;
        }
        System.out.println("");
        System.out.println("Total records read: " +count);
        br.close();
     }

  }
  catch(IOException ioe)
  {
     System.out.println("display_names: Exception opening the file");
  }

}//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 LastName)
{
  //Declare variables to hold file types
  File file = new File(filename);      
  this.findMe = LastName;

  //try to open the file for reading
  try
  {
     if(file.exists()){ 
         BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
         String s="", line = null;
         int count = 0;
         while((line = br.readLine()) != null){
            String [] parts = line.split(",");
            if(parts[0].equals(findMe)){
                count = 1;
                s= line;
            }
         }
         System.out.println("\n"+s+"\n");
         System.out.println("Total matching records found: " +count);
         br.close();

     }
  }
  catch(IOException ioe)
  {
     System.out.println("search: Exception opening the file");
  }


}//end of search

}//end of class

Tester Code:

import java.util.*;

public class TestContactList
{

   /**
   main
   */
   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 an address file for a particular last name ");
         System.out.println("2) Display all last names and first names in the 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 4 exit program
         */
         if(choice == FOUR)
         {
            System.exit(0);
         }
         /*
            if 1 call search method
         */
         if(choice == ONE)
         {
            System.out.print("Enter name to find: ");
            String findMe = scan.nextLine();

            cl.search(findMe);

         }

         /*
            if 2 call display_names method
         */
         if(choice == TWO)
         {
            cl.display_names();
         }
         /*
            if 3 call new_record method
         */
         if(choice == THREE)
         {
            cl.new_record();
         }

      }//end of while loop

   }//end of main


}

thanks in advance xD, I think this should be a simple fix

Was it helpful?

Solution

well, it seems that the data files are the ones missing here :-) but from your code

while((line = br.readLine()) != null){
  s += line;
  count++;
}
System.out.println("\n"+s+"\n");

it seems that you're appending your items into "s" and only in the end you're embracing it between newlines.

Instead, I think you should add the newline inside the while loop.

Of course, there are other issues like using StringBuilder or StringBuffer to concatenate strings.

OTHER TIPS

Your format string (String.format) needs to have a line separator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top