-2

I am writing a program to choose between different shape and then input the values (e.g. radius) to calculate the volume of the shape using JOptionPane, I did some input validation, but the problem is whenever I press the cancel button of the JOptionPane.showInputDialog, the program crash with the following error, where is the problem comes from? And how can I solve it? Thanks!

while(choice.equalsIgnoreCase("y")) { 
    .......

    if (n== JOptionPane.YES_OPTION)
    {

        while (notDone) {
              try { 
              radiusStr = JOptionPane.showInputDialog("Please enter the radius of the sphere");
              radius = Double.parseDouble(radiusStr);
              notDone = false;
              }
              catch (NumberFormatException e ){
                    JOptionPane.showMessageDialog(null, "Input error!  Please enter a number.");
                    continue;
                  }
              volume = new CircularVolume(radius);
C.Le
  • 1

1 Answers1

1

The null pointer exception occurred because you clicked on the cancel button.

According to the docs, showInputDialog returns null when you press the "Cancel" button.

This means that radiusStr here:

radiusStr = JOptionPane.showInputDialog("Please enter the radius of the sphere")

is null.

To avoid this exception, you should do a check first, before parsing it as an int:

if (radiusStr != null) {
   radius = Double.parseDouble(radiusStr);
   notDone = false;
} else {
    //since you are in a while loop here, I suggest you do:
    continue;
    // this will make the input dialog be shown again.
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Here you can find the relevant documentation, if you want to include it in your answer: [docs](https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showInputDialog(java.awt.Component,%20java.lang.Object,%20java.lang.String,%20int,%20javax.swing.Icon,%20java.lang.Object[],%20java.lang.Object)) - ***Returns:*** *user's input, or null meaning the user canceled the input* – BackSlash Feb 27 '18 at 08:15
  • @BackSlash thanks for the info! – Sweeper Feb 27 '18 at 08:17