gpt4 book ai didi

java - 读取文本文件中的字符串

转载 作者:行者123 更新时间:2023-11-30 06:54:48 25 4
gpt4 key购买 nike

假设我的文本文件中有以下文本:

VOTED/1/hannah/18
NOT VOTING/2/janice/20

我有这段代码:

File Orig_outFile = new File("C:\\voters.txt");
BufferedReader infile = new BufferedReader(new FileReader(Orig_outFile));

vNum=JOptionPane.showInputDialog("Enter voters number: ");
String line="";
String something="VOTED";
while(infile.readLine()!=null){
line=infile.readLine();
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();
}
}
infile.close();

任务是用户需要输入一个选民号码,然后读取文本文件,然后如果发现文本文件中的info[0]包含VOTED 它将收到错误消息并需要再次输入其选民号码。我假设我在这里的错误是我使用了 while 循环两次?

最佳答案

实际上,您正在通过执行 infile.readLine() 读取 while 中的一行,并通过执行 将下一行附加到 String line >infile.readLine() 再次。

您最终只读取了文件的第二行。您应该按如下方式更改 while 循环:

while((line = infile.readLine()) != null)

并删除下面的语句:

line = infile.readLine();

这是更正后的代码片段:

File Orig_outFile = new File("C:\\voters.txt");
BufferedReader infile = new BufferedReader(new FileReader(Orig_outFile));

vNum = JOptionPane.showInputDialog("Enter voters number: ");
String line = null;
String something = "VOTED";
while((line = infile.readLine()) != null) {
String [] info = line.split("/");

/* Assuming You Are Entering Voter's Number & Not Voter's Name */
if(info[1].equalsIgnoreCase(vNum)) {
if(info[0].equalsIgnoreCase(something)) {
JOptionPane.showMessageDialog(null, "Voter already voted or
Voter not registered. Please try again");
/* Please Note That You Are Currently Iterating File */
/* If You Do This Here, You'll End Up Checking Same Records */
/* You'll Have To Replace Outer `if` with `while` */
vNum = JOptionPane.showInputDialog("Enter voters number: ");
} else {
President();
break;
}
}
}
infile.close();

这里有一个更清晰的实现方法:

  1. 读取内存中的完整文件(最好是 Map with key -> Voter Number)。

  2. 从用户那里获取选民编号并检查它是否存在于 map 中。

  3. 如果它在 Map 中不存在或者值等于 VOTED 则重复步骤 2

这是代码片段:

File Orig_outFile = new File("C:\\voters.txt");
BufferedReader infile = new BufferedReader(new FileReader(Orig_outFile));
Map<String,String> map = new HashMap<>();
String something = "VOTED";

String line = null;
while((line = infile.readLine()) != null) {
String [] info = line.split("/");
map.add(info[1],info[0]);
}
infile.close();

while(true) {
vNum = JOptionPane.showInputDialog("Enter Voter's Number: ");
if(map.contains(info[1]) && !map.get(info[1]).equalsIgnoreCase(something)) {
President();
break;
} else {
JOptionPane.showMessageDialog(null, "Voter already voted or
Voter not registered. Please try again");
}
}

关于java - 读取文本文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014273/

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