繁体   English   中英

从文件中打印数据

[英]Printing data from a file

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM