简体   繁体   中英

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

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, ie numbers.get("Seven") will return null , because you've put "seven" , not "Seven" there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM