[英]Printing data from a file
So I am stuck trying to search a file for keywords in a sentence and print the found sentence. 因此,我一直试图在文件中搜索句子中的关键字并打印找到的句子。 I have some code which searching the input for matching words but I do not know how to go around searching a file for those keywords based on user input. 我有一些代码在输入中搜索匹配的单词,但是我不知道如何根据用户输入在文件中搜索那些关键字。 Am I going in the right direction? 我朝着正确的方向前进吗?
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;
}
Use contains()
for each word you are looking for and increment a counter once you hit a match. 对要查找的每个单词使用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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.