1

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.in);
        System.out.println("Enter a number in word form: (Example: Five, Six,     Seven): ");
        number = input.next();
        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):
five
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}

1
  • Much better to use Map<String, Integer> numbers = new HashMap<>(). And you don't need to explicitly create Integer objects, Java autoboxing will do it for you: numbers.put("one", 1) Commented Apr 5, 2015 at 20:12

1 Answer 1

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

// wait for input
String number = input.next(); 

// 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.