2014-02-17 28 views
0

我試圖讓哈希表中的一個響應顯示,當我輸入嗨,但它顯示哈希集中的所有項目任何幫助下面會做的感謝是我的代碼。我如何生成隨機響應

public class tst { 
    public static void main(String[] args){ 
     Scanner input=new Scanner(System.in); 

     HashMap<String,HashSet> map = new HashMap<String, HashSet>(); 
     HashSet<String>hs=new HashSet<String>(); 

     Random r = new Random(); 

     hs.add("How are you"); 
     hs.add("Whats up"); 
     hs.add("How Have You Been"); 
     hs.add("Missed Me"); 
     hs.add("ab"); 
     hs.add("cd"); 
     hs.add("Excuse me no no"); 

     map.put("hi",hs);     

     System.out.println("enter Hi"); 
     String str=input.next().toLowerCase().trim(); 

     if(map.containsKey(str)){ 
      System.out.println(map.get(str)); 
     } 
    } 
} 
+4

這是因爲您正在打印'map.get(str)',它是整個'Set'。 –

+0

如果我需要單獨打印一張我錯過了什麼? – user3320908

+3

爲什麼不使用'ArrayList '而不是'HashSet ',然後隨機抽出一個String:'map.get(str).get(r.nextInt(myArrayList.size())) ;'......這樣的事情? – GameDroids

回答

0

我改變你的代碼,並使用ArrayList<String>代替HashSet<String>的。我不知道,如果你進一步的設計,你需要它是一個HashSet,但與ArrayList您可以通過檢索其索引的元素 - 和索引是很容易得到隨機:

public static void main(String args[]) { 
    Scanner input = new Scanner(System.in); 

    // the HashMap now needs to store Strings and ArrayLists 
    HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); 
    // the ArrayList replaces your HashSet. 
    ArrayList<String> list = new ArrayList<String>(); // I called it list so you we can see the difference :) 

    Random r = new Random(); 

    list.add("How are you"); 
    list.add("Whats up"); 
    list.add("How Have You Been"); 
    list.add("Missed Me"); 
    list.add("ab"); 
    list.add("cd"); 
    list.add("Excuse me no no"); 

    map.put("hi", list); 

    System.out.println("enter Hi"); 
    String str = input.next().toLowerCase().trim(); 

    if (map.containsKey(str)) { 
     ArrayList<String> tmpList = map.get(str); // this is just make the step clear, that we now retrieve an ArrayList from the map 
     int randomNumber = r.nextInt(tmpList.size()) // a random number between 0 and tmpList.size() 
     System.out.println(tmpList.get(randomNumber)); // get the random response from the list 
    } 
} 

當我測試了它的結果是這樣的:

enter Hi 
Hi 
How Have You Been 
+0

非常感謝它的工作... – user3320908