sorting - NullPointerException using java.util.Arrays.sort() -


this program reads lines of input file , stores them array words. each element in words[] put character array , sorted alphabetically. each sorted character array assigned string , strings populate array sortedwords. need sort elements in sortedwords array. nullpointerexception when use arrays.sort(sortedwords).

public static void main(string[] args) throws filenotfoundexception {     scanner scanner = new scanner(system.in);     system.out.print("enter file name: ");     system.out.flush();      string filename = scanner.nextline();     file file = new file(filename);      string[] words = new string[10];     string[] sortedwords = new string[10];      try {            filereader fr = new filereader(file);         bufferedreader br = new bufferedreader(fr);          string line = br.readline();         int = 0;          while(line != null) {             words[i] = line.tostring();    // assigns lines array             line = br.readline();    // set line null, terminating loop              string signature = words[i];                                     char[] characters = signature.tochararray();                     arrays.sort(characters);             string sorted = new string(characters);                             sortedwords[i] = sorted;    // assigns each signature array             sortedwords[i] = sortedwords[i].replaceall("[^a-za-z]", "").tolowercase();    // removes non-alphabetic chars , makes lowercase             arrays.sort(sortedwords);               system.out.println(words[i] + " " + sortedwords[i]);             i++;         }          }       catch(ioexception e) {         system.out.println(e);     } } 

you should take sort out of while loop.

int = 0; while(line != null) {    ...    i++; } arrays.sort(sortedwords, 0, i);  

the problem call sort before finished populating sortedwords array. array therefore still contains null strings , these cause nullpointerexception.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -