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

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

문제

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

도움이 되었습니까?

해결책

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

다른 팁

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


    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top