Array of strings in Java NULL pointer exception -
i want make array of strings
i not have fixed size it
as must initialized, intialize null .. give java null pointer exception ???
in part of code , loop on array print contents.. how on error without having fixed size
public static string[] suggest(string query, file file) throws filenotfoundexception { scanner sc2 = new scanner(file); longestcommonsubsequence obj = new longestcommonsubsequence(); string result=null; string matchedlist[]=null; int k=0; while (sc2.hasnextline()) { scanner s2 = new scanner(sc2.nextline()); while (s2.hasnext()) { string s = s2.next(); //system.out.println(s); result = obj.lcs(query, s); if(!result.equals("no match")) {matchedlist[k].equals(result); k++;} } return matchedlist; } return matchedlist; }
if don't know size, list better.
to avoid npe, have initialize list :
list<string> matchedlist = new arraylist<string>();
arraylist example, can use king of list needed.
and element instead of matchedlist[index]
have :
macthedlist.get(index);
so our code :
public static string[] suggest(string query, file file) throws filenotfoundexception { ... list<string> matchedlist= new arraylist<string>(); ... while (sc2.hasnextline()) { scanner s2 = new scanner(sc2.nextline()); while (s2.hasnext()) { ... if(!result.equals("no match")){ //this line strange. see explanation below matchedlist.get(k).equals(result); k++; } } return matchedlist; } return matchedlist; }
there strange in code :
matchedlist.get(k).equals(result);
when that, compare both value , return true or false. it's possible want add value on list, in case have :
matchedlist.add(result);
Comments
Post a Comment