Question

Am trying to get one of the responses in the Hashset to display when i enter hi but its displaying all the items in the hashset any any assistance will do thanks below is my code.

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));
        }
    }
}
Was it helpful?

Solution

I changed your code and used an ArrayList<String> instead of a HashSet<String>. I don't know if in your further design you need it to be a HashSet but with an ArrayList you can retrieve elements by their index – and an index is easy to get randomly:

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

When I tested it the result was this:

enter Hi
Hi
How Have You Been
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top