gpt4 book ai didi

java - 在文件中搜索字符串并返回该特定行

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:54:44 26 4
gpt4 key购买 nike

我正在研究学生注册系统。我有一个文本文件,其中每一行都存储了学生姓名、学生编号和学生成绩,例如:

 name1,1234,7
name2,2345,8
name3,3456,3
name4,4567,10
name5,5678,6

如何搜索姓名然后返回整个句子?查找名称时未找到任何匹配项。

我现在的代码是这样的:

public static void retrieveUserInfo()
{
System.out.println("Please enter username"); //Enter the username you want to look for
String inputUsername = userInput.nextLine();


final Scanner scanner = new Scanner("file.txt");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
break;
}
else System.out.println("Nothing here");
}

最佳答案

问题出在 Scanner(String) 构造函数上:

public Scanner(java.lang.String source)

Constructs a new Scanner that produces values scanned from the specified string.

Parameters: source - A string to scan

它对文件一无所知,只知道字符串。因此,此 Scanner 实例可以为您提供的唯一行(通过 nextLine() 调用)是 file.txt

简单的测试是:

Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());

您应该使用 Scanner 类的其他构造函数,例如:

Scanner(InputStream)
Scanner(File)
Scanner(Path)

关于java - 在文件中搜索字符串并返回该特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695865/

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