【发布时间】:2016-07-03 02:17:02
【问题描述】:
假设我的文本文件包含以下内容:
NOT VOTED/1/gello/18
NOT VOTED/2/tara/24
排列就像status if user already voted or not/voter's number/name/age我把信息线分成数组所以是这样的
info[0]=status/info[1]=voters number/info[2]=name/info[3]=age
这是我的程序的功能:
- 读取文件
- 让用户输入选民编号
- 如果选民人数与 info[1] 匹配,则继续执行步骤 3
- 当 info[0] 包含“VOTED”时,它将收到一条错误消息,表明该选民的号码已经投票并输入另一个选民号码。如果为假,它将进入投票过程
- 现在 info[0] 将更改为“已投票”
这是我的代码:
File original = new File("C:\\voters.txt");//open the original file
File temporary = new File("C:\\tempvoters.txt");//create temporary file
BufferedReader infile = new BufferedReader(new FileReader(original));//read the file
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));//write the data
vNum=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
String something="VOTED";
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(vNum)){
while(info[0].matches(something)) {
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
}
President();
Vice_President();
info[0]="VOTED";
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
else{
outfile.println(line);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();//delete the original file
temporary.renameTo(original);//rename the temporary file to original file
现在这发生在我制作的代码中:
假设我输入1 作为选民号码。并且因为 info[0] 仍然包含“NOT VOTED”,它将继续进行投票过程,之后 info[0] 的元素现在包含“VOTED”。现在在该过程之后它将返回主菜单。现在,当我再次输入另一个选民号码时,我尝试再次输入1 以查看它是否会出现错误消息。它做了。所以我再次输入了另一个选民的号码2,它的信息[0]仍然包含“未投票”,但错误消息仍然会出现!!我真的被这个过程困住了,我不知道该怎么办了,因为我真的不知道出了什么问题。认为我的程序的这种方法中的功能与我拥有的其他方法相同。请帮帮忙
【问题讨论】:
标签: java arrays loops text-files file-handling