java - NullPointerException error in a for loop -
i have method , every time try put value in foo
array nullpointerexception. tried solve dont know why tells me nullpointerexception. thank helping :)
mine = " 0 2 3 "; try { for(int = 0; < mine.length(); i++) { string k = "" + mine.charat(i); if(k.equals(" ") == false) j++; } } catch(exception r) { toast.maketext(this, "bad", toast.length_short).show(); } try { int[] foo = new int[j]; for(int = 0; < mine.length(); i++) { string k = "" + mine.charat(i); if(k.equals(" ") == false) { string = "" + mine.charat(i); mynum = integer.parseint(a); foo[i-1] = mynum; } } } catch(exception df) { toast.maketext(this, "bad", toast.length_short).show(); }
- what
mine
? if null null pointer exception. - use meaningful varaible names.
j
not meaningful. - learn how compare characters.
- i suggest using nm style bracing, personal preference.
- learn how use java collections.
- learn how access array index. starts @ 0, 0 - 1 out of bounds.
- if going use arrays not in sync (foo values not @ same index mine values), use 2 index variables (perhaps mineindex , fooindex).
- catch exceptions name. not catch exception. if insist on catching exception, consider adding comment: "// suck @ programming" catch blocks.
option 1
list valuelist = new linkedlist(); try { (int index = 0, index < mine.length(); ++ index) { final char current = mine.charat(index); if (current != ' ') { valuelist.add(integer.valueof(current)); } } } catch (nullpointerexception exception) { ... something. } catch (numberformatexxception exception) { ... something. }
option 2 - terrible
int valuecount = 0; try { (int index = 0, index < mine.length(); ++ index) { if (mine.getat(index) != ' ') { ++valuecount; } } } catch (nullpointerexception exception) { ... something. } if (valuecount > 0) { try { int[] foo = new int[valuecount]; int valueindex = 0; (int index = 0, index < mine.length(); ++ index) { final char current = mine.charat(index); if (current != ' ') { foo[valueindex++] = integer.valueof(current)); } } } catch (nullpointerexception exception) { ... something. } catch (numberformatexxception exception) { ... something. } }
Comments
Post a Comment