基于字符串输入返回响应的Java方法

时间:2014-09-21 18:35:57

标签: java

我对编程还很陌生,而且我还没有完全理解那里的每一种方法。正如我的指示在代码中所说,我需要在给定某个字符串输入时打印出某个输出。我迷失了该做什么,而且我也只是谷歌搜索它。我很感激帮助!我想知道我可以实现什么方法以及调用什么方法。

/**
 * This method returns a response based on the string input: "Apple" =>
 * "Orange" "Hello" => "Goodbye!" "Alexander" => "The Great" "meat" =>
 * "potatoes" "Turing" => "Machine" "Special" => "\o/" Any other input
 * should be responded to with: "I don't know what to say."
 * 
 * @param input
 * The input string
 * @return Corresponding output string.
 */
public static String respond(String input) {

    // This method returns a response based on the string input:
    // "Apple" => "Orange"
    // "Hello" => "Goodbye!"
    // "Alexander" => "The Great"
    // "meat" => "potatoes"
    // "Turing" => "Machine"
    // "Special" => "\o/"
    // Any other input should be responded to with:
    // "I don't know what to say."
    return "this string is junk";
}

1 个答案:

答案 0 :(得分:1)

我使用map

private static final DEFAULT_RESPONSE = "I don't know what to say.";
private static final Map<String, String> RESPONSES = new HashMap<>();
static {
    RESPONSES.put("Apple", "Orange");
    RESPONSES.put("Hello", "Goodbye!"
    RESPONSES.put("Alexander", "The Great"
    RESPONSES.put("meat", "potatoes"
    RESPONSES.put("Turing", "Machine"
    RESPONSES.put("Special", "\o/"
}

public static String respond(String input) {
    String response = RESPONSES.get(input);
    if (response == null) {
        response = DEFAULT_RESPONSE;
    }
    return response;
}