java - How can I Generate a Random Response -
Trying to get one of the responses in the hashaseet when I enter Hello, but display all items in the hash Any help given below is my code.
public class tst {public static void main} (string [] args) {scanner input = new scanner (System.in); HashMap & LT; String, HashSet> Map = new hashmap & lt; String, hashase & gt; (); Hasheset & lt; String & gt; HS = new hashset & lt; String & gt; (); Random R = New Random (); Hs.add ("How are you"); Hs.add ("what happened"); H. S.D. ("How did you do it"); Hs.add ("Missed Me"); Hs.add ("ab"); Hs.add ("cd"); Hs.add ("I'm sorry"); 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)); }}}}
I changed my code and a ArrayList & lt ; String & gt;
a HashSet & lt; String & gt; Instead of
I do not know that in your next design you should have it HashSet
, but with an ArrayList
you can retrieve the elements from their index And it is easy to get an index randomly:
public static zero main (string algos []) {scanner input = new scanner (System.in); //Hashmap now needs to store strings and array listsHap & lt; String, array list & lt; String & gt; & Gt; Map = new hashmap & lt; String, Arlist & lt; String & gt; & Gt; (); // Arrayist changes your Hashet's ArrayList & LT; String & gt; List = New Arrestist & lt; String & gt; (); // I called it in the list so that you can see the difference :) Random R = new random (); List.add ("How are you"); List.add ("Whats up"); List.add ("How are you"); List.add ("Missed Me"); List.add ("ab"); List.add ("cd"); List.add ("Sorry I do not know"); Map.put ("hi", list); System.out.println (Enter "Hi"); String str = input.next (). ToLowerCase (). Trim (); If (map.containsKey (str)) {ArrayList & lt; String & gt; TmpList = map.get (str); // This is just clear the steps, that we now get an ArrayList between the map int randomNumber = r.nextInt (tmpList.size ()) // a random number 0 and tmpList.size () System.out.println ( TmpList.get (randomNumber)); // Get a random response from the list}}
When I tested it, the result was:
Hi how it's done
Comments
Post a Comment