Comment attribuer une action spécifique au ( « Annuler ») bouton dans (JOptionPane.showInputDialog) en Java?

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

Question

Voici ma question avec un code court exemple:

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

* Le problème avec le code ci-dessus est que lorsque je clique sur le bouton « annuler », le programme frappe les deux erreurs:. (Le hors de portée et l'entrée non valide)

S'il vous plaît suggestions comment je peux résoudre ce problème?

Merci d'avance

Était-ce utile?

La solution

D'abord, vous devez vérifier si l'entrée est nulle. Sinon, vous utilisez parseDouble dessus.

Comme ceci:

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

Aussi, essayez de ne pas prendre des exceptions en mettant « Exception », comme vous l'avez fait. Essayez toujours de préciser l'exception que vous recherchez autant que possible. Dans ce cas, vous devez utiliser NumberFormatException au lieu d'exception.

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

Autres conseils

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


    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top