gpt4 book ai didi

Java搜索文件

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:57 25 4
gpt4 key购买 nike

我有 2 个字符串变量:

givenAccnt”是从用户获取的输入字符串

accntToken”是一行文本的子字符串(第一个字符串)

如果给定的 Accnt 等于 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...
}

关于Java搜索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com