gpt4 book ai didi

java - 扫描 txt 文件时在每一行之前获取 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:03 25 4
gpt4 key购买 nike

我在读取 txt 文件和使用 java 的 scanner.util 查找单词/模式时遇到问题。目前正在测试读数,我在每一行的前面都得到了空值。在那个问题之后,我仍然不确定如何在 txt 文件中搜索模式/单词。我还必须显示包含模式/单词的行。

public class SearchPattern {
public static void main(String[] args) throws IOException{
Scanner s = new Scanner(System.in);
String pattern;
String filename;
String[] text = new String[10];
System.out.println("Enter the filename");
filename = s.nextLine();
System.out.println("Enter the pattern you'd like to search");
pattern = s.nextLine();
// Print out each line that contains pattern
// may need an array to store StringS of lines with word
try{
s = new Scanner(new BufferedReader(new FileReader(filename)));
int x = 0;
while (s.hasNext()) {
text[x] += s.next();
x++;
}
}
finally {
if (s != null) {
s.close();
}
}
text[0] = "test";
System.out.println(text[0]);
for(String txt : text){
System.out.println(txt);
}
}
}

最佳答案

你这样做:

text[x] += s.next();

这意味着:text[x]null 而不是您附加 s.next()

替换为:

text[x] = s.next();

关于java - 扫描 txt 文件时在每一行之前获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14842929/

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