Search code examples
javadebuggingtreemap

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.


Solution

  • 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()));
        }
    }