java - 从文件打印数据

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

最佳答案

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

相关文章:

java - 抑制控制台中的 rjava 错误输出

java - 对象相同但输出不同?请帮忙

java - java中用元素返回名称的方法?

java - 证书颁发者必须列在 Java 的 'cacert' keystore 中才能被信任吗?

java - 如何发出 Http Get 快速请求?

java - 如何基于多个不同的 URI 构建查询

java - 我应该在哪里存储我的游戏关卡状态?

java - 为什么在我的例子中,protocol buffer 的性能比 JSON 差?

java - 自动生成默认和字段构造函数的 eclipse 快捷方式是什么?

java - 集群环境下共享java HashMap