Nick Wilson Nick Wilson - 3 years ago 134
Java Question

Java hashtable, with a while loop

This is what I need and what I got.
Add the numbers 3 through 10 to the hashtable
Prompt the user for a string, and display the corresponding number.
Using a loop and a single println statement, display all of the values (both strings and integers) in a table.
My main problem is I'm not sure what to do with the while loop. I have only worked with a while loop once.

import java.util.*;
class HTDemo {
public static void main(String args[]) {
Hashtable<String, Integer> numbers = new
Hashtable<String, Integer>();

numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
numbers.put("four", new Integer(4));
numbers.put("five", new Integer(5));
numbers.put("six", new Integer(6));
numbers.put("seven", new Integer(7));
numbers.put("eight", new Integer(8));
numbers.put("nine", new Integer(9));
numbers.put("ten", new Integer(10));

String number;
Scanner input = new Scanner(;
System.out.println("Enter a number in word form: (Example: Five, Six, Seven): ");
number =;
while () {
System.out.println("You entered: " + number + "\nwhich is the interger: " + numbers);

This is what I get, it's not right to the instructions:

Enter a number in word form: (Example: Five, Six, Seven):


You entered: five

which is the integer: {three=3, six=6, ten=10, seven=7, nine=9, one=1, five=5, four=4, two=2, eight=8}

Answer Source
Scanner input = new Scanner(; 
System.out.println("Enter a number in word form: (Example: Five, Six, Seven): "); 

// wait for input
String number =; 

// display value, using Map#get method
System.out.println(String.format("You've entered %s which is integer %s", number, numbers.get(number)));  

// iterate over map entries using for (not while) loop
for (Map.Entry<String, Integer> e : numbers.entrySet()) {
    System.out.println(String.format("Number:%s, integer:%s", e.getKey(), e.getValue())); 

Btw, you should not forget that strings are case-sensitive, i. e. numbers.get("Seven") will return null, because you've put "seven", not "Seven" there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download