Implement the randomresponse solution discussed in slide 20
Solution
import java.util.ArrayList;
import java.util.Random;
/**
* Program 1
*
* @author
*
*/
public class RandomTester {
private ArrayList<String> responses;
/**
* default constructor to declare and add 5 elements
*/
public RandomTester() {
// TODO Auto-generated constructor stub
responses = new ArrayList<String>();
responses.add(\"yes\");
responses.add(\"dont know\");
responses.add(\"no\");
responses.add(\"Good\");
responses.add(\"i know\");
}
/**
* method to get the response from arraylist with the random index from 0 to
* size
*
* @return
*/
public String getResponse() {
Random random = new Random();
return responses.get(random.nextInt(responses.size()));
}
public static void main(String[] args) {
RandomTester randomTester = new RandomTester();
System.out.println(randomTester.getResponse());
}
}
OUTPUT:
no
import java.util.HashMap;
/**
* Program 2
*
* @author
*
*/
public class PhoneBookTest {
/**
* @param args
*/
public static void main(String[] args) {
// declaration hashmap of string key and value
HashMap<String, String> phoneBook;
phoneBook = new HashMap<String, String>();
// adding values to hashmap
phoneBook.put(\"Charles Nguyen\", \"(531)9392 4587\");
phoneBook.put(\"Lisa Jones\", \"(402)4536 4674\");
phoneBook.put(\"William H.Smith\", \"(998)5488 0123\");
// get the phone number using key
String phoneNumber = phoneBook.get(\"Lisa Jones\");
// print the value
System.out.println(phoneNumber);
}
}
OUTPUT:
(402)4536 4674

