java - 创建具有多个单词的扫描仪
问题描述
我需要包含 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 时,什么也没有出现。
解决方案
当您调用 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?");
}
推荐阅读
- chef-infra - 厨师客户端错误:Errno::ENOENT:没有这样的文件或目录@ rb_sysopen - /etc/chef/chef_guid
- java - 如何在 Android Oreo 中获取字符串的 Base64 表示
- javascript - 构建动态 BottomNavigation NS 6.5 的问题
- python - 基于.xlsx的子目录中文件的批量重命名
- c# - 通过 curl、asp.net 发布不同的二进制文件
- regex - Ansible regex_search/regex_findall
- javascript - 我目前正在阅读 Eloquent JavaScript 并且正在尝试解决递归测试,但我的代码一直给我一个“未定义”的反馈
- ruby-on-rails - 我应该将 JSON 数据集播种并规范化到我的关系数据库中还是使用其他方法?
- python - Zapier - 输入数据无法形成有效负载
- java - 在for循环中创建多个arraylist对象并将其添加到TreeMap