【问题标题】:Java Reading File and output to console [closed]Java读取文件并输出到控制台[关闭]
【发布时间】:2014-05-16 00:49:29
【问题描述】:

所以我有一个小问题,由于某种原因,我正在消隐,我尝试将它移动到循环内部并返回到循环外部它不起作用。在返回方法 display_names 的选项二中,它从文件中读取它们,并将它们写入控制台的一行而不是两行。

例如:

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

主代码:

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

测试代码:

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


}

提前感谢 xD,我认为这应该是一个简单的修复

【问题讨论】:

  • final int FOUR = 4; 真的吗?您希望数字 FOUR 的定义在未来某个时间点发生变化吗? final int EXIT = 4;是 const 类型变量的适当使用。 final int DISPLAY = 2;,我希望你能明白这一点。
  • 大声笑,当我读到它时我想知道同样的事情 XD,那是给我们的代码:p
  • 应该是老师吧?难怪如果他们被教导这样的废话,那么很难找到值得雇用的毕业生

标签: java bufferedreader filereader


【解决方案1】:

好吧,数据文件似乎是这里缺少的文件 :-) 但来自您的代码

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

您似乎将您的项目附加到“s”中,最后您才在换行符之间拥抱它。

相反,我认为您应该在 while 循环中添加换行符。

当然,还有其他问题,比如使用 StringBuilder 或 StringBuffer 连接字符串。

【讨论】:

  • 知道了,使用不同的阅读方式 XD
【解决方案2】:

您的格式字符串 (String.format) 需要有一个 line separator

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2016-06-05
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    相关资源
    最近更新 更多