开发者社区 问答 正文

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

我刚刚开始学习如何编写程序。在这个程序中。我正在尝试使用扫描仪在句子中查找单词。但是,我遇到了一个问题。我的代码如下:

import java.util.Scanner;

public class TestOne {
    static Scanner 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)返回“不匹配”。在if与else语句都是相同的,我的投入(pick==6)也是相同的字符串(pick==5)。所以我想这是因为扫描仪吧?

展开
收起
几许相思几点泪 2019-12-05 15:31:10 300 分享 版权
阿里云 AI 助理回答

你的代码中确实存在一些问题,让我们一步步来分析和解决。

首先,注意到你直接在代码中使用了 pick 变量,但没有给它赋值。在 Java 中,这样会导致编译错误,因为变量 pick 在使用前必须有明确的初始化或赋值。你应该从用户那里获取 pick 的值,或者至少为它提供一个默认值以便测试。

其次,在处理 pick == 6 的情况时,你连续调用了两次 scn.nextLine()。第一次是在读取句子之后立即调用,这实际上丢弃了用户输入的下一行(可能是一个空行),而不是你想要的行为。应该去掉多余的那一次调用。

修正后的代码如下:

import java.util.Scanner;

public class TestOne {
    static Scanner scn = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Please enter a number (5 or 6):");
        int pick = scn.nextInt(); // 添加这一行来获取 pick 的值

        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");
            }
        } else {
            System.out.println("Invalid input. Please enter 5 or 6.");
        }
    }
}

这段修改后的代码首先通过 scn.nextInt() 获取用户输入的 pick 值,然后在处理 pick == 6 的分支时去掉了多余的 scn.nextLine() 调用,以确保正确读取用户的输入。记得在实际应用中处理可能出现的 nextInt() 后跟 nextLine() 时的缓冲问题,这里由于我们只做了一次 nextInt() 调用并紧接着读取句子,所以通常不会遇到这个问题。

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