1
我有2個字符串變量:爪哇搜索文件
「givenAccnt」是從用戶
「accntToken」而獲得的輸入字符串爲文本行
的的子串(第一串)如果givenAccnt 等於 accntToken,我想返回行的與accntToken匹配的文本。
此外,可能存在超過1個匹配的情況。我想將所有匹配保存到一個變量,然後一次返回這些匹配(行)。
以下代碼僅在最後一行返回匹配。 (如果匹配是在其他線路錯過它)
我似乎無法確定它爲什麼這樣表現。
任何幫助,將不勝感激。
givenAccnt = searchTextField.getText();//else, user is using search field to get given account
try
{
scanner = new Scanner(file); //initialize scanner on file
while(scanner.hasNextLine()) //while lines are being scanned
{
getLine = scanner.nextLine(); //gets a line
int i = getLine.indexOf(' '); //get first string-aka-accnToken
accntToken = getLine.substring(0, i);
}
if(givenAccnt.equals(accntToken)) //if match
{
collectedLines = new StringBuilder().append(getLine).toString();
psswrdLabels = new JLabel(collectedLines, JLabel.LEFT);
psswrdLabels.setAlignmentX(0);
psswrdLabels.setAlignmentY(0);
fndPwrdsCNTR += 1; //counter for number of passwords found
JOptionPane.showMessageDialog(null, psswrdLabels ,+fndPwrdsCNTR+" PASSWORD(S) FOUND!", JOptionPane.INFORMATION_MESSAGE); //shows window with matched passwords (as JLabels)
searchTextField.setText(""); //clears search field, if it was used
}else
//..nothing found
}catch (FileNotFoundException ex) {
//..problem processing file...
}
當您使用調試程序遍歷代碼時,您發現了什麼?你爲什麼每次找到匹配時都創建一個新的'StringBuilder'?只需將匹配追加到'StringBuilder'。這段代碼是否編譯,'+ fndPwrdsCNTR +「密碼(S)找到!」應該是一個語法錯誤。 –
嗨,Jonny,是的,+ fndPwrdsCNTR +「密碼(S)發現!」編譯。我看到了這個愚蠢的錯誤,將再次嘗試。謝謝.. – codEinsteinn