Asker
Asker

Reputation: 1685

Working with TreeMaps (21.9- Intro to Java, Liang, 10th Edition)

I'm supposed to write a program that returns the capital of a given state in the U.S. using TreeMaps. However, the program returns null when I run it, before I even get a chance to input anything. Can someone tell me what's wrong?

public class Map {

  private TreeMap<String, String> pairs;

  public Map() {
    pairs = new TreeMap<String, String>();
  }

  public void readFrom(String fileName) {
    Scanner input = null;
    try {
        input = new Scanner(new File(fileName));
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }

    while (input.hasNext(" , ")) {
        pairs.put(input.next(), input.next());
    }
  }

  public String get(String key) {
    return pairs.get(key);
  }

}

public static void main(String[] args) {

    Map USA = new Map();
    USA.readFrom("states_and_capitals.txt");

    System.out.print("Enter a state: ");
    Scanner input = new Scanner(System.in);
    System.out.println(USA.get(input.toString()));
}

The text file that the program reads from, "states_and_capitals.txt", is formatted such that on each line there's a state and its capital, separated by a comma (no spaces), like so:

Alabama,Montgomery

Alaska,Juneau

Arizona,Phoenix

etc.

Upvotes: 1

Views: 83

Answers (2)

Omar Mainegra
Omar Mainegra

Reputation: 4184

Check this, I fix the part where you read from text file and populate the TreeMap. I tested and works fine.

public class Map {

    private TreeMap<String, String> pairs;

    public Map() {
        pairs = new TreeMap<String, String>();
    }

    public void readFrom(String fileName) {
        try {
            Scanner input = new Scanner(new File(fileName));
            while (input.hasNextLine()) {
                String [] parts = input.nextLine().split(",");
                if (parts.length == 2)
                    pairs.put(parts[0], parts[1]);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    public String get(String key) {
        return pairs.get(key);
    }

    public static void main(String[] args) {
        Map USA = new Map();
        USA.readFrom("states_and_capitals.txt");

        System.out.print("Enter a state: ");
        Scanner input = new Scanner(System.in);
        System.out.println(USA.get(input.nextLine()));
    }
}

Upvotes: 1

Dangling Piyush
Dangling Piyush

Reputation: 3676

For reading String input using scanner you should use below

scanner.nextLine();

So in your code you should do

System.out.print("Enter a state: ");
Scanner input = new Scanner(System.in);
String stateName=input.nextLine();
System.out.println(USA.get(stateName));

Use Enter after giving input as statename.

Upvotes: 0

Related Questions