java - Not sure why I'm getting a NullPointerException error -
so i'm running program various things string array. 1 of them inserting string inside array , sorting it. i'm able use sort method, when attempt insert string , sort nullpointerexception. code:
import java.util.scanner; import java.io.*; public class list_driver { public static void main(string args[]) { scanner keyboard = new scanner(system.in); int choice = 1; int checker = 0; string [] words = new string[5]; words[0] = "telephone"; words[1] = "shark"; words[2] = "bob"; listwb first = new listwb(words); int menu = uwb.geti("1. linear seach\n2. binary search\n3. insertion in order\n4. swap\n5. change\n6. add\n7. delete\n8. insertion sort\n9. quit\n"); switch(menu) { //other cases case 3: { string insert = uwb.gets("what term inserting?"); first.insertioninorder(insert); first.display(); }//not working break; }//switch menu }//main }//list_driver
uwb basic util driver. doesn't have problems. listwb file itself:
public class listwb { public void insertionsort() { for(int = 1; < size; i++) { string temp = list[i]; int j = i; while(j > 0 && temp.compareto(list[j-1])<0) { list[j] = list[j-1]; j = j-1; } list[j] = temp; } } public void insertioninorder(string str) { insertionsort(); int index = 0; if(size + 1 <= list.length) { while(index < size && str.compareto(list[index])>0) index++; size++; (int x = size -1; x> index; x--) list[x] = list[x-1]; list[index] = str; } else system.out.println("capacity reached"); }//insertioninorder }//listwb
how fix this?
you have array of 5 strings, 3 of them initialized. rest points null (because did not initialize them):
string [] words = new string[5]; words[0] = "telephone"; words[1] = "shark"; words[2] = "bob"; words[3] = null; words[4] = null;
the first line initializes array itself, not containing objects.
but insert iterates on 5 elements. , temp null, when 3. statement temp.compareto throws nullpointerexception.
for(int = 1; < size; i++) { string temp = list[i]; int j = i; while(j > 0 && temp.compareto(list[j-1])<0)
solution: check temp null in while loop. or not use string array @ auto-resizable data structure list java.util.arraylist.
Comments
Post a Comment