我有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。而是在读取行之前创建它。代码:

givenAccnt = searchTextField.getText();//else, user is using search field to get given account
try
   {
builder=new StringBuilder();//initialize builder to store matched lines
      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 = builder.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...
                    }

10-04 14:01