开发者社区 问答 正文

使用扫描仪时找不到句子中的单词

我刚刚开始学习如何编写程序。在此程序中,我尝试使用扫描仪在句子中查找单词。但是我遇到了这个问题。导入java.util.Scanner;

公共类testone {static Sc​​anner scn = new Scanner(System.in);

public static void main(String[] args) {
    if (pick == 5) {
        String sentenceFive = "i see you";
        String wordFive = "you";

        if (sentenceFive.contains(wordFive)) {
            System.out.println("Keyword matched the string");
        }

        else {
            System.out.println("No match");
        }
    }

    else if (pick == 6) {
        System.out.println("Please enter a sentence");
        String sentenceFive = scn.nextLine();
        scn.nextLine();
        System.out.println("Please enter a word");
        String wordFive = scn.nextLine();

        if (sentenceFive.contains(wordFive)) {
            System.out.println("Keyword matched the string");
        }

        else {
            System.out.println("No match");
        }

    }
}
}

(pick == 5)完全可以,但是(pick == 6)返回“ No match”。if,else语句是相同的,我对(pick == 6)的输入也与(pick == 5)中的字符串相同。所以我想这可能是因为扫描仪问题?

有办法解决吗?先感谢您

展开
收起
几许相思几点泪 2019-12-05 14:57:35 350 分享 版权
阿里云 AI 助理回答

你好!很高兴你开始学习编程。根据你的代码,我注意到在处理pick == 6的情况时,有一个潜在的误解导致了问题。

问题在于这段代码:

scn.nextLine(); // 这一行是多余的
System.out.println("Please enter a word");
String wordFive = scn.nextLine();

在这段代码中,你调用了两次scn.nextLine()。第一次调用实际上读取了用户输入的句子之后的换行符,并没有真正读取任何有用的输入。因此,当接下来尝试读取单词时,你可能已经错过了用户的实际输入。

解决这个问题的方法很简单,就是移除多余的scn.nextLine();调用,修改后的代码如下:

else if (pick == 6) {
    System.out.println("Please enter a sentence");
    String sentenceFive = scn.nextLine();

    System.out.println("Please enter a word");
    String wordFive = scn.nextLine();

    if (sentenceFive.contains(wordFive)) {
        System.out.println("Keyword matched the string");
    } else {
        System.out.println("No match");
    }
}

这样修改后,程序应该能够正确地接收并比较用户输入的句子和单词了。记得在进行此类调试时,密切关注每一步的数据流动,确保没有意外地跳过或重复处理输入数据。祝你学习进步!

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答地址: