【问题标题】:How can I Generate a Random Response如何生成随机响应
【发布时间】:2014-02-17 21:52:38
【问题描述】:

我试图在我输入 hi 时显示 Hashset 中的响应之一,但它显示了 hashset 中的所有项目,任何帮助都将在下面感谢我的代码。

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));
        }
    }
}

【问题讨论】:

  • 那是因为你正在打印map.get(str),这是整个Set
  • 如果我需要单独打印一份我还缺少什么?
  • 你为什么不直接使用ArrayList&lt;String&gt; 而不是HashSet&lt;String&gt; 然后随机拉出一个字符串:map.get(str).get(r.nextInt(myArrayList.size())); ..类似的东西?

标签: java hashmap hashset


【解决方案1】:

我更改了您的代码并使用了ArrayList&lt;String&gt; 而不是HashSet&lt;String&gt;。我不知道在您的进一步设计中是否需要将其设为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

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 2013-12-08
    • 2017-05-10
    • 2011-02-19
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多