我有一个程序可以存储、读取和保存联系人信息。但是,名称只能在没有空格的情况下读取(例如 Tony)。如果我想让程序可以读取带空格的单词(例如 Tony Arnold),我应该怎么做?
联系人:
import java.io.*;
import java.util.*;
public class Contacts {
int ARRAY_SIZE = 20;
Contact data[] = new Contact[ARRAY_SIZE];
Scanner k = new Scanner(System.in);
public void readFile() {
File file = new File("contact.txt");
try {
Scanner f = new Scanner(file);
StringTokenizer st = new StringTokenizer(f.nextLine(",") );
int count1 = 0;
while(f.hasNext() && count1 < ARRAY_SIZE){
Contact c = new Contact();
c.setName(f.next());
c.setPhone(f.next());
c.setDepartment(f.next());
data[count1] = c;
count1++;
}
}
catch (FileNotFoundException e) {
System.out.println("Error: input file not found");
System.exit(1);
}
}
public void displayData() {
for(int i=0;i<ARRAY_SIZE;i++){
Contact c = data[i];
if(c !=null)
System.out.println(i+": "+c.getName()+" "+c.getPhone()+" "+c.getDepartment());
}
}
public void doEdit() {
try{
System.out.println("Enter the record number to edit:");
int num = k.nextInt();
Contact c = data[num];
if(c!=null){
System.out.println("Enter the new name: ");
c.setName(k.next());
System.out.println("Enter the new phone: ");
c.setPhone(k.next());
System.out.println("Enter the new department: ");
c.setDepartment(k.next());
System.out.println();
System.out.println("Done!");
System.out.println();
}
else{
System.out.println("Record number is not used.");
}
}
catch(ArrayIndexOutOfBoundsException | InputMismatchException e){
System.out.println("Record number is out of range.");
}
}
public void saveFile() {
try{
PrintWriter pw = new PrintWriter("contact.txt");
for(Contact c : data){
if(c !=null){
pw.println(c.getName()+", "+c.getPhone()+", "+c.getDepartment());
}
}
pw.close();
}
catch(FileNotFoundException e){
System.out.println("Error: Can't save file");
}
}
public void process() {
boolean done = false;
while(!done){
System.out.println("PRESS 1 to view all records");
System.out.println("PRESS 2 to edit a record");
System.out.println("PRESS 3 to exit");
System.out.println(">");
String ans = k.next();
switch(ans){
case "1":
displayData();
break;
case "2":
doEdit();
break;
case "3":
done = true;
break;
default:
System.out.println("Invalid option");
}
}
}
public static void main(String[] args) {
Contacts cl = new Contacts();
cl.readFile();
cl.process();
cl.saveFile();
}
}
联系人:
package lab3;
public class Contact {
private String name;
private String phone;
private String department;
private String id;
public String getName() {
return name;
}
public void setName(String tempName) {
name = tempName;
}
public String getPhone() {
return phone;
}
public void setPhone(String tempPhone) {
phone = tempPhone;
}
public String getDepartment() {
return department;
}
public void setDepartment(String tempDepartment) {
department = tempDepartment;
}
public String getid() {
return id;
}
public void setid(String tempid) {
id = tempid;
}
}
联系人.txt:
Tony 897 eng
Toby 999 math
Yvonne 123 comp
听说将 contact.txt 文件更改为 .csv 并使用 StringTokenizers 可以帮助程序使用逗号而不是空格读取姓名、电话、部门。我该怎么做?
您是正确的,将文件中联系人数据的格式更改为 CSV(逗号分隔值)并使用
StringTokenizer
类来解析文件的每一行将是处理带空格的联系人姓名的好方法。以下是您可以修改代码以执行此操作的方法:
Tony Arnold,897,eng
Toby Smith,999,math
Yvonne Lee,123,comp
readFile
方法,使用StringTokenizer
解析CSV文件的每一行,使用逗号作为分隔符:public void readFile() {
File file = new File("contact.csv");
try (Scanner f = new Scanner(file)) {
int count1 = 0;
while (f.hasNext() && count1 < ARRAY_SIZE) {
String line = f.nextLine();
StringTokenizer st = new StringTokenizer(line, ",");
Contact c = new Contact();
c.setName(st.nextToken().trim());
c.setPhone(st.nextToken().trim());
c.setDepartment(st.nextToken().trim());
data[count1] = c;
count1++;
}
} catch (FileNotFoundException e) {
System.out.println("Error: input file not found");
System.exit(1);
}
}
此代码读取 CSV 文件的每一行,使用
StringTokenizer
类将其拆分为多个字段,并从这些字段创建一个 Contact 对象。 trim()
方法用于从每个字段中删除任何前导或尾随空格。
saveFile
方法,将联系人数据写入文件时使用逗号分隔字段:public void saveFile() {
try (PrintWriter pw = new PrintWriter("contact.csv")) {
for (Contact c : data) {
if (c == null) {
continue;
}
pw.println(String.join(", ", c.getName(), c.getPhone(), c.getDepartment()));
}
} catch (FileNotFoundException e) {
System.out.println("Error: Can't save file");
}
}
此代码在将联系人数据写入文件时使用逗号分隔字段。
通过这些更改,您的程序应该能够处理带空格的联系人姓名。
附言在更新的代码 if 方法
readFile()
中,Scanner
实例是在 try-with-resources 语句的括号内创建的。然后执行 try 块的主体,并且在退出 try 块时自动关闭 Scanner 实例,无论是正常还是由于异常。这确保Scanner
实例始终正确关闭,简化了代码,并减少了资源泄漏的机会。请注意,您不再需要显式调用 f.close()
,因为它已由 try-with-resources 语句处理。与saveFile()
方法和PrintWriter
类变量类似。