2014-09-21 73 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