Java 通过查询输入和if语句非常方便
我对编程完全是新手,只是在玩弄我目前所知道的东西。我正在制作一种原始的“人工智能”,可以问一些简单的问题。在代码的这一部分,程序会问“你住在哪里?”和“你喜欢住在那里吗?”我试图这样做,如果用户输入的不是“否”或“是”的变体,机器人会再次问这个问题。这是我到目前为止所拥有的Java 通过查询输入和if语句非常方便,java,Java,我对编程完全是新手,只是在玩弄我目前所知道的东西。我正在制作一种原始的“人工智能”,可以问一些简单的问题。在代码的这一部分,程序会问“你住在哪里?”和“你喜欢住在那里吗?”我试图这样做,如果用户输入的不是“否”或“是”的变体,机器人会再次问这个问题。这是我到目前为止所拥有的 System.out.println("I have never been to " + line3 + " before. Do you like it there?"); // Wait for
System.out.println("I have never been to " + line3 + " before. Do you like it there?");
// Wait for user to enter a line of text
String line4 = input.nextLine();
if(line4.equals("Yes")){
System.out.println("That's good! I'm glad to hear it.");
}
else if(line4.equals("No")){
System.out.println("Oh no! You should move then!");
}
else if(line4.equals("no")){
System.out.println("Oh no! You should move then!");
}
else if(line4.equals("yes")){
System.out.println("That's good! I'm glad to hear it.");
}
我该怎么做呢?还有,有没有更简单的方法来完成我已经在代码中编写的内容?我必须为每一个不同的是/否做出一个else-if语句,例如,我需要一个不同的else-if来表示“是”或“根本不!”等
非常感谢提前一个选项,使用无限循环(和
equalsIgnoreCase
);像
另一个选项,使用a和循环,如
Map<String, String> msgMap = new HashMap<>();
msgMap.put("yes", "That's good! I'm glad to hear it.");
msgMap.put("no", "Oh no! You should move then!");
// ...
String line4;
do {
line4 = input.nextLine().toLowerCase();
if (msgMap.containsKey(line4)) {
System.out.println(msgMap.get(line4));
}
} while (!msgMap.containsKey(line4));
那么你可以这样称呼它
if (getYesOrNo(input, "Do you like living there?")) {
System.out.println("That's good! I'm glad to hear it.");
} else {
System.out.println("Oh no! You should move then!");
}
您可以将ask函数移动到单独的方法中,并在递归中使用它(或将其与Elliott Frisch answer合并): 因此,现在您可以这样使用它:
String prevLine = "Boston";
String question = "I have never been to " + prevLine + " before. Do you like it there?";
boolean answer = askUser(question);
if (answer) {
System.out.println("That's good! I'm glad to hear it.");
} else {
System.out.println("Oh no! You should move then!");
}
或者再次将其包装在地图中您的代码不完整,请输入完整的代码。。。。。您可以使用忽略大小写,而不是将
no
和no
分开。
if (getYesOrNo(input, "Do you like living there?")) {
System.out.println("That's good! I'm glad to hear it.");
} else {
System.out.println("Oh no! You should move then!");
}
public static boolean askUser(String question) {
System.out.println(question);
String answer = input.nextLine();
if ("yes".equalsIgnoreCase(answer)) {
return true;
} else if ("no".equalsIgnoreCase(answer)) {
return false;
} else {
return askUser(question);
}
}
String prevLine = "Boston";
String question = "I have never been to " + prevLine + " before. Do you like it there?";
boolean answer = askUser(question);
if (answer) {
System.out.println("That's good! I'm glad to hear it.");
} else {
System.out.println("Oh no! You should move then!");
}