在Java中扫描匹配关键字的整个用户输入

时间:2015-04-11 03:21:49

标签: java

所以我很难找到一个与用户输入的句子相匹配的关键字。我没有输入一个字符串,而是输入整个句子并检查关键字的句子。这是我工作的一些代码但由于某种原因我无法扫描整个句子以获得匹配的关键字。

input = scanner.nextLine().toLowerCase();
    for (int i = 0; i < keywords.length; i++) {
        if (keywords[i].equalsIgnoreCase(input)) {
            System.out.println("Found keyword!");
            // TODO: You can optimize this
        }
    }

以及关键字列表

 String[] keywords = { "day", "What book", "professor name", "office",
            "hour", "e-mail", "name", "major", "student e-mail",
            "group id", "group name", "lecture", "lecture room",
            "lecture time", "number of lectures", "current lecture",
            "topics of current lecture", "number of test",
            "date of a test", "number of assignments", "sure",
            "current assignment", "due day" };

2 个答案:

答案 0 :(得分:1)

 String[] keywords = {"day", "What book", "professor name", "office",
            "hour", "e-mail", "name", "major", "student e-mail",
            "group id", "group name", "lecture", "lecture room",
            "lecture time", "number of lectures", "current lecture",
            "topics of current lecture", "number of test",
            "date of a test", "number of assignments", "sure",
            "current assignment", "due day"};

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine().toLowerCase();

        for (String keyword : keywords) {
            if (input.contains(keyword)) {

                System.out.println("Found keyword match  , " + keyword);

            }

尝试上面的代码,检查你的输入句子是否包含任何给定的关键字。

答案 1 :(得分:0)

您当前正在存储输入文件中的整行文本,并将其与关键字进行比较。假设每行有多个单词,则代码将无效。

我有两个我能想到的选择。一种是在String:

上使用contains方法
input = scanner.nextLine().toLowerCase();
for (int i = 0; i < keywords.length; i++) {
    if (input.contains(keywords[i])) {
        System.out.println("Found keyword!");
        // TODO: You can optimize this
    }
}

根据您尝试完成的内容,您可能需要查看StringTokenizer课程。这使您可以使用句子并查看每个单词。