2015-10-26 66 views
2

這就是我所要做的:我想製作一個程序,要求用戶輸入:你的名字。如何讀取字符串中的字符並根據輸入返回?

這是我需要幫助的:然後,我希望程序讀取名稱中的每個字符,字母。最後,我想讓它返回與用戶名中每個字符對應的形容詞列表。

這是我到目前爲止有:

public static void main (String [] args) { 

    System.out.println("This program will give meanings to every " 
         + "letter in your name.\n"); 

    Scanner input = new Scanner (System.in); 
    System.out.println("Please enter your name:"); 
    String name = input.next(); 

    String A = "adventurous"; 
    String B = "bold"; 
    String C = "caring"; 
    String D = "devoted"; 
    String E = "encouraging"; 
    String F = "funny"; 
    String G = "gentle"; 
    String H = "honest"; 
    String I = "intelligent"; 
    String J = "joyful"; 
    String K = "kind"; 
    String L = "loving"; 
    String M = "mature"; 
    String N = "neat"; 
    String O = "organized"; 
    String P = "persistent"; 
    String Q = "quick"; 
    String R = "religious"; 
    String S = "sensitive"; 
    String T = "thankful"; 
    String U = "useful"; 
    String V = "virtuous"; 
    String W = "witty"; 
    String X = "this letter isn't in your name"; 
    String Y = "young"; 
    String Z = "zany"; 
} 
+1

您需要更多標籤。這是什麼語言?我認爲這是JAVA,但其他人都知道嗎? –

+0

你看到了什麼輸出/錯誤? –

+0

@WillSheppard我只收到兩條打印聲明: 「這個程序會給你的名字中的每一個字母賦予意義。」 「請輸入你的名字。」 當我輸入我的名字並點擊輸入時,由於代碼不完整,因此沒有任何反應。 –

回答

3

把你的形容詞在地圖(對於char關鍵和形容詞的值),而不是使用這些字符串,則名轉換爲CharArray,遍歷它併爲每個字母從Map中獲取項目。您可以將您的形容詞放入列表中,然後再打印出來。

//create the map and the list of adjectives 
Map<Character, String> adjectives = new HashMap<>(); 
List<String> personAdjectives = new ArrayList<>(); 
//fill the map (although it would be better retrieving data from a database) 
adjectives.put('a',"adventurous"); 
adjectives.put('b',"bold"); 
// ... 
//convert the name to a char array 
char[] chars = name.toCharArray(); 
//iterate over it 
for(char c : chars){ 
    //access the map and fill the list 
    personAdjectives.add(adjectives.get(c)); 
} 
//print the list 
+0

我得到一個錯誤: 「Map ...」 - 它說我必須插入「Dimensions」。我搜索並將其更改爲: 「HashMap <字符串,字符> ...」 - 請問您的建議是否正確? –

+0

是的,但你必須顛倒順序。我已經用正確的順序更新了我的答案。 – Aurasphere

+0

太棒了,謝謝!顯然我也必須做一個Char類。 –

相關問題