简体   繁体   中英

How can I loop a try catch for a JOptionPane?

I'm trying to get the user to type in a double, and make them type it again in case it's not a double until it's a correct value. The current code I have is this one:

while (!baseEsValida) {
            try {
                base = Double.parseDouble(JOptionPane.showInputDialog(ventana, "Introduce la base"));
                baseEsValida = true;
            } catch (NumberFormatException e) {
                base = Double.parseDouble(JOptionPane.showInputDialog(ventana, "Número inválido para la base, inténtelo otra vez"));
            }
        }

So my goal is to repeat the "Invalid number" message as many times as necessary, but it only appears once. That is, if the user types in an incorrect number the first time, the catch message appears, but if they type again an incorrect value, it crashes. What can I do? Thanks in advance!

I tried following, based on your code:

boolean correctInput = false;
double base = 0;
String str = "Enter a double value";
    
while (!correctInput) {
       try {
          base = Double.parseDouble(JOptionPane.showInputDialog(str));
          correctInput = true;
       } catch (NumberFormatException e) {
          str = "Wrong format, enter a double value";
       }
}
    
System.out.println(base);

Edit:

public static void main(String[] args) {
        boolean correctInput = false;
        double base = 0;
        String str = "Enter a double value";
        
        do {
            try {
                base = Double.parseDouble(JOptionPane.showInputDialog(str));
                correctInput = true;
            } catch (NumberFormatException e) {
                str = "Wrong format, enter a double value";
            }
        } while (!correctInput);
        
        System.out.println(base);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM