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