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


i'm supposed write program returns capital of given state in u.s. using treemaps. however, program returns null when run it, before chance input anything. can 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 state: ");     scanner input = new scanner(system.in);     system.out.println(usa.get(input.tostring())); } 

the text file program reads from, "states_and_capitals.txt", formatted such on each line there's state , capital, separated comma (no spaces), so:

alabama,montgomery

alaska,juneau

arizona,phoenix

etc.

check this, fix part read text file , populate treemap. tested , 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 state: ");         scanner input = new scanner(system.in);         system.out.println(usa.get(input.nextline()));     } } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -