读取是否匹配/包含文本文件中的选民号码

时间:2016-03-14 12:24:32

标签: java text file-handling

例如我的文本文件包含:

1/hannah/18
2/jeorge/20

这个安排就像votersnumber/name/age现在我希望我的程序读取文件,确定文本文件中的votersnumber是否包含用户输入的选民编号然后执行以下程序。如果文件不包含/匹配用户输入的内容,程序将使用户再次输入选民号码。

我试过这个代码:

File Orig_outFile = new File("C:\\Users/Regz-pc/workspace/lozada/voters.txt");
    BufferedReader infile = new BufferedReader(new FileReader(Orig_outFile));

    String voters[]=new String[10+1]; //purpose of this is to determine whether the voter already voted. the [10+1] is not final but just a sample/just for test. but i will still be using this
    String allVoters="";
    for(int index=1;index<voters.length;index++){
        voters[index]="NOT VOTED YET";
        allVoters=allVoters+"voter["+index+"]="+voters[index]+"\n";
        }

    vNum2=Integer.parseInt(JOptionPane.showInputDialog("Enter voters number: "));//user will enter the voters number
    vNum=Integer.toString(vNum2);
    String line=null;

    while((line=infile.readLine())!=null){
        String [] info=line.split("/");//divide the votersnumber/name/age
        if(!info[0].contains(vNum) && voters[vNum2].contains("VOTER ALREADY VOTED")){//determine if the vNum2 exist in text file
                JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
                vNum2=Integer.parseInt(JOptionPane.showInputDialog("Enter voters number: "));
                }
        else{
            voters[vNum2]="VOTER ALREADY VOTED";
            JOptionPane.showMessageDialog(null, allVoters);

            President();
        }
    }
    infile.close();

但是这段代码只会执行一次,但之后会执行错误消息Voter already voted or Voter not registered. Please try again会出现,然后会让用户再次输入选民号码然后返回主菜单。当我再次尝试执行这个程序时,它会让我输入一个选民的号码然后再回到主菜单。

2 个答案:

答案 0 :(得分:0)

这不是有效的java条件,

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

改为使用:

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

并阅读以下内容:

String line= "";
while(infile.readLine() !=null){
    // read the line
    line=infile.readLine()

    // res of your code...
}

答案 1 :(得分:0)

if(!info[0].contains(vNum) && voters[vNum2].contains("VOTER ALREADY VOTED")){//determine if the vNum2 exist in text file
    JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
    vNum2=Integer.parseInt(JOptionPane.showInputDialog("Enter voters number: "));
}

在这里,你需要改变vNum,我认为。