首页 > 解决方案 > 创建具有多个单词的扫描仪

问题描述

我需要包含 10 个变量,但是当我输入任何内容时,它只会出现 1 个变量,我需要知道如何制作它,例如,当输入“游戏”时,程序会返回“你喜欢游戏吗? " 现在,我输入的任何内容都会出现“你喜欢大学吗?”

我已经尝试搜索谷歌 3 个小时,并完成了他们所说的一切,但我找不到它。由于某种原因,使用 .contains 不起作用。

    Scanner chatterbot = new Scanner(System.in);    
    String uni = ("University");
    String gaming = ("Gaming");

    uni = chatterbot.nextLine();
    if (uni.contains("University"))
        System.out.println("Do you like uni?");
    uni = chatterbot.nextLine();
    if (uni.contains("Yes"))
        System.out.println("Do you study one of SE CS or IT?");
    else if (uni.contains("No"))
        System.out.println("Do you study one of SE CS or IT?");
    uni = chatterbot.nextLine();
    if (uni.contains("Yes"))
        System.out.println("That is really great!");
    else if (uni.contains("No"))
        System.out.println("That is not good!");
    System.exit(0);


    gaming = chatterbot.nextLine();
    if (gaming.contains("Gaming"))
        System.out.println("Do you like gaming?");
    gaming = chatterbot.nextLine();
    if (gaming.contains("Yes"))
        System.out.println("What kind of games do you like to play?");

我希望输出是如果用户键入 Uni 然后它会说“你喜欢 uni 吗?” 当你输入游戏时,它会显示“你喜欢游戏吗?” uni 部分有效,但是当我键入 Gaming 时,什么也没有出现。

标签: java

解决方案


当您调用 chatterbot.nextLine() 时,您的输入会被消耗,因此如果您再次调用 nextLine() 它会等待下一个输入。但是通过将输入保存在一个变量中,您可以将其与多个值进行比较。

这应该有效:

Scanner chatterbot = new Scanner(System.in);    
String input = chatterbot.nextLine();
if (input.contains("University")) {
   System.out.println("Do you like uni?");
} else if (input.contains("Gaming")) {
   System.out.println("Do you like gaming?");
}

推荐阅读