EastAPOLO EastAPOLO - 1 month ago 7
Java Question

How to check if JOptionPane input dialog contains an int or double with 2 if statements and is converted?

I would like to check if a JOptionPane input dialog containing the text "Enter a number" is an int or double with two if statements. Then I want to convert the int in one if statement and do the same thing in the other with a double and print "The number is" (something). If the user inputs 5 then I expect it to print an integer and if the user inputs 5.3 then I expect a double. Here is my code so far and if you test it you will see it does not work:

int number1Int = 0;
double number1Double = 0.0;
String num1 = JOptionPane.showInputDialog("Enter a number");


if(number1Int == Integer.parseInt(num1)){
number1Int = Integer.parseInt(num1);
JOptionPane.showMessageDialog(null, "The number is " + number1Int);
}
else if(number1Double == Double.parseDouble(num1)){
number1Double = Double.parseDouble(num1);
JOptionPane.showMessageDialog(null, "The number is " + number1Double);
}


Thank you,

EastAPOLO

Answer

You didn't exactly ask a question, but I see a problem with your code that I think might be what you're having trouble with.

You have if(number1Int == Integer.parseInt(num1)) which is only true if the user enters an integer value that is equal to number1Int. Since number1Int is initialized to 0 the only time this condition is true is when the user enters a form of zero that will parse to an integer value like 0, 00, 000, etc.

Similarly you also have else if(number1Double == Double.parseDouble(num1)) which is only true when the user enters some form of zero that parses to a double value - could be 0.0, 0.00, 0000.000000 etc.

What I'm guessing you want is something more like this:

    int number1Int = 0;
    double number1Double = 0.0;
    String num1 = JOptionPane.showInputDialog("Enter a number");

    //EDIT: added boolean flag per comments
    boolean isInt = false;
    try{
        number1Int = Integer.parseInt(num1);
        isInt = true;
        JOptionPane.showMessageDialog(null, "The number is " + number1Int);
    }catch(NumberFormatException e){
        System.out.println("User did not enter an integer.");
    }
    if(!isInt){
        try{
            number1Double = Double.parseDouble(num1);
            JOptionPane.showMessageDialog(null, "The number is " + number1Double);
        }catch(NumberFormatException e){
            System.out.println("User did not enter a double.");
        }
    }