gpt4 book ai didi

java - 从文件打印数据

转载 作者:行者123 更新时间:2023-11-30 03:27:59 26 4
gpt4 key购买 nike

所以我一直试图在文件中搜索句子中的关键字并打印找到的句子。我有一些代码可以在输入中搜索匹配的单词,但我不知道如何根据用户输入在文件中搜索这些关键字。我的方向正确吗?

static String [ ] matchwords = {"get","think","go", "talk","choose"};
static List words = Arrays.asList(matchwords);

public static void main(String args[]){
Scanner console = new Scanner(System.in);
String input = console.nextLine().toLowerCase();
List line = Arrays.asList(input.split(" "));
int numberofWords =0;

numberofWords = check(line, numberofWords);
System.out.println("Matched words is : "+numberofWords);
}

public static int check(List list, int count){
for(int j=0;j<list.size();j++)
if(words.contains(list.get(j))){
list.remove(j);
check(list, count);
count++;
}

return count;
}

最佳答案

对您要查找的每个单词使用 contains() ,并在找到匹配项后递增计数器。

String input = console.nextLine().toLowerCase();
List<Integer> matches = new ArrayList<Integer>();
for (int i = 0; i < matchwords.length; i++) {
if (input.contains(matchwords[i]) {
matches.add(i); // stores indices of the words that had a match
// matches.length will be the number of matches (previously count)
}
}

关于java - 从文件打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708149/

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