Observe the following code, which creates a simple hashtable. // Demonstrate a H
ID: 3755020 • Letter: O
Question
Observe the following code, which creates a simple hashtable. // Demonstrate a Hashtable import java.util.*; class HTDemo { public static void main(String args[]) { Hashtable numbers = new Hashtable(); numbers.put("one", new Double(1.0d)); numbers.put("two", new Double(2.0d)); } } Starting with this provided code, add the following functionality: Add the numbers 3 through 10 to the hashtable continuing in the same manner as shown. Prompt the user for a string, and display the corresponding number. For example, if the user types “five”, the program would output “5.0”. This must be done using the hashtable as created in the previous step. Using a loop and a single println statement, display all of the values (both strings and integers) in a table.
Explanation / Answer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Vamsi
*/
import java.util.*; class HTDemo {
public static void main(String args[])
{
Hashtable numbers = new Hashtable();
numbers.put("one", new Double(1.0d));
numbers.put("two", new Double(2.0d));
//adding numbers 3 to 10
numbers.put("three", new Double(3.0d));
numbers.put("four", new Double(4.0d));
numbers.put("five", new Double(5.0d));
numbers.put("six", new Double(6.0d));
numbers.put("seven", new Double(7.0d));
numbers.put("eight", new Double(8.0d));
numbers.put("nine", new Double(9.0d));
numbers.put("ten", new Double(10.0d));
String s;
Scanner sc = new Scanner(System.in);// to read input
System.out.print("Enter number as string:");
s= sc.next();//reading number
//display corresponding number
System.out.println("Corresponding number for "+s+" :"+numbers.get(s));
//using loop printing all elements of hashtable
System.out.println("Hash table:");
int i=0;
int n =numbers.size();
for( Iterator iter=numbers.keySet().iterator(); iter.hasNext(); ) {
String key = (String) iter.next();
double value = (double) numbers.get( key );
System.out.println(key+" : "+value);
}
}
}
output:
run:
Enter number as string:five
Corresponding number for five :5.0
Hash table:
three : 3.0
six : 6.0
ten : 10.0
seven : 7.0
nine : 9.0
one : 1.0
five : 5.0
four : 4.0
two : 2.0
eight : 8.0
BUILD SUCCESSFUL (total time: 3 seconds)
//pls give a thumbsup if you find it helpful
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.