2014-09-21 42 views
-2

我对编程还很陌生,我并不完全了解每种方法。正如我的方向在代码中所说,我需要在给定某个字符串输入时打印出某个输出。我失去了做什么,我也有麻烦,只是谷歌搜索它。我感谢帮助!我只想知道我可以实施什么方法以及要调用什么。基于字符串输入返回响应的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"; 
} 
+0

你学过的if语句?如果输入是“Apple”,则返回“Orange”等等等等。 – csmckelvey 2014-09-21 18:38:21

+1

地图在这里也可以。 – 2014-09-21 18:40:20

+0

我应该使用扫描仪来获取输入吗?如'userInput.nextLine();' ? – Aladdin 2014-09-21 18:42:06

回答

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; 
} 
+0

我会试试这个。尽管我还没有学到任何关于地图的知识。 – Aladdin 2014-09-21 23:00:45