从文件打印数据

时间:2015-04-17 19:47:14

标签: java

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

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;
}

1 个答案:

答案 0 :(得分:2)

对于您要查找的每个单词使用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)
    }
}