gpt4 book ai didi

Java读取文件并输出到控制台

转载 作者:行者123 更新时间:2023-12-02 05:49:44 30 4
gpt4 key购买 nike

所以我有一个小问题,由于某种原因我正在空白,我尝试将它移到循环内部并移回循环外部,但它不起作用。在返回方法 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,我认为这应该是一个简单的修复

最佳答案

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

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

看起来您正在将项目附加到“s”中,直到最后您才将其包含在换行符之间。

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

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

关于Java读取文件并输出到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23690961/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com