JOptionPane Input to int

kxk picture kxk · Jun 25, 2010 · Viewed 125.9k times · Source

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

Answer

jjnguy picture jjnguy · Jun 25, 2010

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).