我的程序要求用户输入一个13位数字并从文件名中搜索它(“Voter Database.txt”)。现在,如果我编辑一些记录,我需要将其写在另一个名为(“Voter Database Copy.txt”)的文件上。
在同一个程序中,搜索功能最初(必须)从文件名(“Voters Database.txt”)进行搜索,但是如果我更新并将记录复制到新文件,我就会从错误中搜索没有更新的文件。
这是编辑代码。
Scanner in=new Scanner (System.in);
String cnic,vn,list,nm,age,adrs;
try{
BufferedReader br=new BufferedReader(new FileReader("Voters Database.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("Voters Database Copy.txt"));
String s; String s1; String s2;
System.out.println("Enter CNIC to edit the record");
s1=in.nextLine();
System.out.println("Enter New CNIC,if applicable");
cnic=in.nextLine();
System.out.println("Enter New Vote No,if applicable");
vn=in.nextLine();
System.out.println("Enter New List No,if applicable");
list=in.nextLine();
System.out.println("Enter New Name,if applicable");
nm=in.nextLine();
System.out.println("Enter New Age,if applicable");
age=in.nextLine();
System.out.println("Enter New address,if applicable");
adrs=in.nextLine();
s2="CNIC: "+cnic+" Vote Number: "+vn+" List No: "+list+" Name: "+nm+" Age: "+age+" Address: "+adrs;
s=br.readLine();
while(s!=null){
if(s.contains(s1))
{
bw.write(s2);
bw.newLine();
}
else
{
bw.write(s);
bw.newLine();
}
s=br.readLine();
}
br.close();
bw.close();
}
catch(IOException e){
System.err.println("IO EXCEPTION");
}
答案 0 :(得分:0)
根据我的评论,
br.readLine()
并丢弃/忽略返回的结果,即您没有将返回的字符串分配给字符串:line = br.readLine();
除了一次在循环之前。String line = ""
然后while ((line = br.readLine()) != null) {
伪代码解释步骤。在这个阶段确实没有必要使用索引,因为您需要做的就是从BufferedReader读入的每行String上调用contains(...)
。在解析感兴趣的行时,您需要使用indexOf(...)
来提取它包含的数据。
public search method, takes a cnic String parameter, returns a String
declare result String, set = to ""
open file within a try block, create BufferedReader
declare String variable line, assign "" to it
while loop, in condition, read from buffered reader into line, and loop while not null
Check if line contains cnic String. No need for index of here, just contains
if so, assign line to result String.
end while loop
end open file, create BufferedReader
close BufferedReader (or use try with resources)
return result String
end of method
当您想要解析感兴趣的行时,您需要获得几个整数:
"CNIC: "
字符串" Voter Number: "
字符串使用这些数字,尝试提取您的数据......您将获得它。