Search code examples
javaswingjoptionpane

Java: how to return the selection from the "JOptionPane.showInputDialog" as an "int" instead of an "Object"


I have a function that use the following code from here as follow:

public static Object generationMode(){
    Object[] possibleMode = { "M-Sequence", "Gold Code"};
    Object selectedValue = JOptionPane.showInputDialog(null,
            "Choose one", "Input",
            JOptionPane.INFORMATION_MESSAGE, null,
            possibleMode, possibleMode[0]);     
    return selectedValue;       
}

I am calling this function in the main class, and it works fine. however, instead of the "Object ", I want to return an "int" to the main class. I tried to cast the return value as follow:

public static int generationMode(){
    Object[] possibleMode = { "M-Sequence", "Gold Code"};
    int selectedValue = JOptionPane.showInputDialog(null,
            "Choose one", "Input",
            JOptionPane.INFORMATION_MESSAGE, null,
            possibleMode, possibleMode[0]);
    return (int) selectedValue;           // it breaks here 
}

but it is not working. the debugger is saying at the breaking point: (Suspended (exception ClassCastException)) !!!! so what exactly the mistake ?


Solution

  • You can't cast it to an int because it's not returning an int! It is returning a String, which is chosen from Object[] possibleMode = { "M-Sequence", "Gold Code"};.

    You could cast it to a String instead, and make your method return a String.

    Or, if you need the method to return an index:

    return Arrays.asList(possibleMode).indexOf(selectedValue);