Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

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

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}
String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top