****It throws NullPointerException in JOptionPane code as following.****
public static void main(String[]args){
String[] options={"Do it again?", "Exit"};
int response=0;
int indexOfZip;
do{
try{
String dataStr=JOptionPane.showInputDialog("Enter a zip code");
if(dataStr!=null){
while (k<i){
if (place[k].equals(dataStr)){
indexOfZip=k;
k++;
}
}
int data=Integer.parseInt(dataStr);
response=JOptionPane.showOptionDialog(null,
"You asked me to search for zip code:"+dataStr+"The zip code "+dataStr+" belongs to"+place[k].getTown()+","+place[k].getState()+"Do you want me to search again?",
"results",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,options[0]);
System.out.println("You asked me to search for zip code:"+dataStr);
System.out.println("The zip code "+dataStr+" belongs to"+place[k].getTown()+","+place[k].getState());
System.out.println("Do you want me to search again?");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,"Bad Numeric String, try again.", "Input Error",JOptionPane.ERROR_MESSAGE);
}
}while(response==0);
if (response!=0){
System.out.print("No");
System.out.println("Good Bye!");
}
}
The terminal says the exception is for this line response=JOptionPane.showOptionDialog(null,
But I cannot see anything wrong here, because the "response" is initialized before.
It looks like place[k]
must be null
,
and place[k].getTown()
triggers NullPointerException
.
Watch the value of place[k]
in a debugger (or add a print statement).