java - About JOptionPane CANCEL_OPTION -


i not imply cancel option method twice. (both first input dialog box , second input dialog box football) when click cancel button, nullpointerexception error occurs. idea?

public void randomdistribution() {      string[] gametypes = {"nba", "euroleague", "ncaa", "nhl", "football" };     string question = "choose game";     string title = "memory game";     imageicon entry = new imageicon(getclass().getresource("background.jpg"));     string c = (string) joptionpane.showinputdialog(null, question, title,             joptionpane.plain_message, entry, gametypes,gametypes[4]);      if (c.equals("football")) {         string[] f_level = {"easy", "normal", "hard"};         string question_f = "choose level";         string title_f = "memory game - football";         string c2 = (string) joptionpane.showinputdialog(null, question_f, title_f,                 joptionpane.plain_message, null, f_level,f_level[2]);         if (c2.equals("easy")) {             c = "football1";         } else if (c2.equals("normal")) {             c = "football2";         } else if (c2.equals("hard")){             c = "football3";         }     }      (int = 0; < 64; i++) {         picofcells[i] = (int) (math.random() * 64) + 1;         (int j = 0; j < i; j++) {             if (picofcells[i] == picofcells[j] && != j && != 0) {                 --i;             }         }     }      (int = 0; < 64; i++) {         picofcells[i] = (picofcells[i] % 32);         picofallcells[i] = new imageicon(getclass().getresource(picofcells[i] + 1 + c +".gif"));     }     startgame.doclick(); } 

if understand correctly, problem getting nullpointerexception when cancel 1 of 2 dialogs.

taking @ the documentation of joptionpane.showinputdialog(…) explains returned when user cancels input:

returns: user's input, or null meaning user canceled input

so code

string c = (string) joptionpane.showinputdialog(null, question, title,         joptionpane.plain_message, entry, gametypes,gametypes[4]); 

sets c null when user cancels input. because do

if (c.equals("football")) { 

in next line, trying call method equals(…) on null reference, not possible , causes nullpointerexception get. prevent exception being thrown need check c null, e.g. so:

if (c == null) {     // whatever want when user canceled input } else if (c.equals("football")) { 

of course same goes c2… ;-)


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -