Null Pointer Exception with arrays and classes - Java -
ok, have global array part of class "temp". want edit array anywhere in program. working fine. however, when try use values set values in "cords" class, null exception error. have commented in code. idea why?
import java.util.scanner; public class solution { public static void main(string[] args) { scanner inp = new scanner(system.in); int n = 0; for(int k = 0; k<4; k++){ temp.tempvalues[k] = 0; } boolean checknums = false; string coords = ""; while(n<1 || n>2000){ system.out.println("enter number of lines"); n = inp.nextint(); } cords[] lines = new cords[n]; int proceed = 0; inp.nextline(); for(int = 0; i<n; i++){ proceed = 0; checknums = false; while((proceed != 3) || (checknums == false)){ system.out.println("enter line coordinates. "+(i+1)); coords = inp.nextline(); proceed = checkspaces(coords); checknums = rightnums(coords); } lines[i] = new cords(); lines[i].setvalues(temp.tempvalues[0], temp.tempvalues[1], temp.tempvalues[2], temp.tempvalues[3]); } } public static int checkspaces(string sent){ int spaces = 0; for(int y = 0; y< sent.length(); y++){ if(sent.charat(y)==' '){ spaces++; } } return spaces; } public static boolean rightnums(string sent){ int z = 0; int l = 0; string num = ""; while(z<sent.length()){ while((z<sent.length())&&(sent.charat(z) != ' ')){ num += sent.charat(z); z++; } if(integer.parseint(num) < 0 || integer.parseint(num) >=10000){ return false; }else{ temp.tempvalues[l] = integer.parseint(num); num = ""; z++; l++; } } return true; } public class cords{ int x1 = 0; int x2 = 0; int y1 = 0; int y2 = 0; public void setvalues(int xx1, int yy1, int xx2, int yy2){ x1 = xx1; y1 = yy1; x2 = xx2; y2 = yy2; } } public static class temp{ static int[] tempvalues = new int[4]; } }
your lines
array not contain object. contains null
s , can't invoke methods on null
-values.
since iterating on lines
array, initialize current element before invoke methods on it:
for (int = 0; < lines.length; i++) { lines[i] = new cords(); lines[i].setvalues(...); }
you have make cords
class static.
Comments
Post a Comment