非常nooby查询输入和if语句

时间:2016-05-22 04:16:09

标签: java

我对编程完全陌生,而且我只是搞乱到目前为止我所知道的事情。我正在做一个原始的" AI"各种各样的简单问题。在这部分代码中,程序会询问"你住在哪里?"和#34;你喜欢住在那里吗?"我试图这样做,以便如果用户输入任何但不是“或”的变体,机器人将再次提出问题。这是我到目前为止所拥有的

        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.");

        }

我该怎么做呢?此外,是否有更简单的方法来完成我已经在代码中编写的内容?我必须为每个不同的Yes / No做一个else if语句,例如,如果是"是的话,我需要一个不同的其他!"或者"完全没有!"等等。

非常感谢提前

2 个答案:

答案 0 :(得分:1)

一个选项,使用无限循环(和equalsIgnoreCase);像

String line4 = input.nextLine();
while (true) {
    if (line4.equalsIgnoreCase("yes")) {
        System.out.println("That's good! I'm glad to hear it.");
        break;
    } else if (line4.equalsIgnoreCase("no")) {
        System.out.println("Oh no! You should move then!");
        break;
    }
    line4 = input.nextLine();
}

另一种选择,使用Map<String, String>和像

这样的循环
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));

另一个选项是,提取提示并输入辅助方法,如

static boolean getYesOrNo(Scanner scanner, String msg) {
    while (true) {
        System.out.println(msg);
        String v = scanner.nextLine();
        if (v.equalsIgnoreCase("yes")) {
            return true;
        } else if (v.equalsIgnoreCase("no")) {
            return false;
        }
    }
}

然后你可以称之为

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!");
}

答案 1 :(得分:0)

你可以将ask函数移动到一个单独的方法并在递归中使用它(或者将它与Elliott Frisch的答案联系起来):

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!");
    }

或者再次将其包裹在地图中