How to assign a sepecifc action to the (“Cancel”) button within (JOptionPane.showInputDialog) in Java?

StackOverflow https://stackoverflow.com/questions/4608124

Question

Here is my question with a short sample code:

 double num = 0.00;

try
{
    num = Double.parseDouble(JOptionPane.showInputDialog("Enter your num:"));

}

catch (Exception e)
{
    System.err.println("Error: Invalid Input!");
    JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
    "Error", JOptionPane.ERROR_MESSAGE);
}

//Validate the num

if (num > 0.0 && num <= 1000.00)
{
    functionA();
}

else if (deposit <= 0.0 || deposit > 1000.00)
{
 System.err.println("Error: out of range");
}

*The Problem with the above code is that when i click the "cancel" button, the program is hitting both errors: (the out of range and the invalid input).

Please any suggestions how i can fix this?

Thanks in advance

Was it helpful?

Solution

First, you need to verify if the input is null. If not, then you use parseDouble on it.

Like this:

try
{
    String i = JOptionPane.showInputDialog("Enter your num:");
    if (i != null)
        num = Double.parseDouble(i);
}

Also, try to not catch exceptions by putting "Exception", like you did. Always try to specify the exception you are looking for as much as possible. In this case, you should use NumberFormatException instead of just Exception.

catch (NumberFormatException e)
{
    System.err.println("Error: Invalid Input!");
    JOptionPane.showMessageDialog(null, "Error: Invalid Input!",  
    "Error", JOptionPane.ERROR_MESSAGE);
}

OTHER TIPS

package org.life.java.so.questions;

import java.text.ParseException;
import javax.swing.JOptionPane;

/**
 *
 * @author Jigar
 */
public class InputDialog {

    public static void main(String[] args) throws ParseException {
        String input = JOptionPane.showInputDialog("Enter Input:");
        if(input == null){
            System.out.println("Calcel presed");
        }else{
            System.out.println("OK presed");
        }


    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top