JAVA: How to enter data into a Hashtable using a scanner?

advertisements

I want to be able to enter in a (name, age) into the scanner and store it in a hashtable. so far it is not going well.

public static void main(String[] args) {
    Hashtable<String, Integer> names = new Hashtable<String, Integer>();
    Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String name = in.nextLine();
            int age = in.nextInt();
            names.put(name, age);
        }
    }


In case you want the next token to be read as a String you should use next() method and not nextLine(). nextLine() returns the line that was skipped not the current line, as you think.

From nextLine() javadoc :

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

Returns: the line that was skipped

Changing :

String name = in.nextLine();

to

String name = in.next(); will fix your problems. Thats's all you have to do.

Further on, you need some condition to end reading the input. You can use some sort of a keyword, and when that keyword is read you know is time to end reading the input.

A complete and tested example here :

private static final String EXIT_KEYWORD = "exit";

public static void main(final String[] args) {
    Hashtable<String, Integer> names = new Hashtable<String, Integer>();
    Scanner in = new Scanner(System.in);
    while (in.hasNext()) {
        String name = in.next();
        if (EXIT_KEYWORD.equals(name)) {
            break;
        }
        int age = in.nextInt();
        names.put(name, age);
    }

    for (Map.Entry<String, Integer> entry : names.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}