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();     } 

  1. what mine? if null null pointer exception.
  2. use meaningful varaible names. j not meaningful.
  3. learn how compare characters.
  4. i suggest using nm style bracing, personal preference.
  5. learn how use java collections.
  6. learn how access array index. starts @ 0, 0 - 1 out of bounds.
  7. if going use arrays not in sync (foo values not @ same index mine values), use 2 index variables (perhaps mineindex , fooindex).
  8. 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

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -