Exception in thread "main" java.lang.NullPointerException in Dictionary Code -
code:
import java.util.scanner; public class dictionary { private static string fwordmap; private string fword; private static string fmeaning; public dictionary (string wordmap, string word, string meaning) { fwordmap = wordmap; fword = word; fmeaning = meaning; } public dictionary() { } public string lookupword(string word) { boolean isworddefined = fwordmap.contains(word); if (isworddefined = true) { system.out.println(fmeaning); } if (isworddefined = false) { system.out.println("unknown"); } homecoming word; } public boolean isworddefined (string word, string fwordmap) { boolean isworddefined = fwordmap.contains(word); homecoming isworddefined; } public boolean addword(string word, string meaning, string fwordmap) { boolean isworddefined = fwordmap.contains(word); if (isworddefined == false) { fwordmap = fwordmap +"|" +word+"|" +meaning +"|"; } else { system.out.println("the word" +word +"is in dictionary"); system.out.println("quit"); } homecoming isworddefined; } public static void main (string[]args) { dictionary mydictionary = new dictionary(); { system.out.println("command?"); scanner in = new scanner (system.in); string command = in.nextline(); system.out.println("word?"); string word = in.nextline(); string add together = "add"; string lookup = "lookup"; system.out.println("meaning?"); string meaning = in.nextline(); if (command == add) { fwordmap = fmeaning +"|" +word+"|" +meaning +"|"; } if (command == lookup) { meaning = mydictionary.lookupword(word); system.out.println("the meaning is:" +meaning); } boolean worddefined = fwordmap.contains(word); //line 76 while (worddefined == false) { system.out.println("command?"); command = in.nextline(); system.out.println("word?"); word = in.nextline(); system.out.println("meaning?"); meaning = in.nextline(); if (command == add) { fmeaning = fmeaning +"|" +word+"|" +meaning +"|"; } if (command == lookup) { meaning = mydictionary.lookupword(word); system.out.println("the meaning is:" +meaning); } } } } }
error: exception in thread "main" java.lang.nullpointerexception @ dictionary.main(dictionary.java:76)
you using default constructor in main method. , constructor fwordmap
not initialized.
so @ line #76 fwordmap
null , hence npe.
boolean worddefined = fwordmap.contains(word);
there 2 things can do:
call constructor initializes values. default constructor initialize variables default values. java exception null
No comments:
Post a Comment