views:

40

answers:

3

Hello all, I am trying to make a JOptionPane get an input and assign it to an int but I am getting some problems with the variable types.

I am trying something like this:

Int ans = (Integer) JOptionPane.showInputDialog(frame,
            "Text",
            JOptionPane.INFORMATION_MESSAGE,
            null,
            null,
            "[sample text to help input]");

But I am getting:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot
be cast to java.lang.Integer

Which sounds logical yet, I cannot think of another way to make this happen.

Thanks in advance

+1  A: 

Simply use:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

You cannot cast a String to an int, but you can convert it using Integer.parseInt(string).

jjnguy
Hmm... it seems I need to also add int ans = Integer.parseInt( JOptionPane.showInputDialog(frame, "Text", JOptionPane.INFORMATION_MESSAGE, null, null, "[sample text to help input]").toString());
devilwontcry
@devil If you use the correct form of `showinputdialog` you won't need to do that. But, you are correct in some cases.
jjnguy
I see I see. If I may ask one more thing, is there a way, using a loop maybe, to check if the input given actually is an integer or not? Sth like: ... do { ans = JOptionPane.showInputDialog(...) } until ans = integer ?
devilwontcry
Oh nevermind, I got it!
devilwontcry
A: 

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
Jack
I understand, thank you!
devilwontcry
A: 

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

davyM