比方說,我在我的文本文件,這樣的文字:閱讀文本文件中的字符串
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'資源。 – Raedwald