1

The method is supposed to create as many buttons, as it is given Strings and then return the selected String. Eclipse says that my return statement doesnt return a String. How do I have to write the return statement for it to do so?

private static  String getActionDialog(String... actions) {

    JRadioButton[] buttons = new JRadioButton[actions.length];
    ButtonGroup group = new ButtonGroup();

    for (int i = 0; i < actions.length; i++) {
        buttons[i] = new JRadioButton(actions[i]);
        group.add(buttons[i]);
    }

    buttons[0].setSelected(true);

    Object[] message = buttons;
    Object[] options = { "OK", "Cancel" };
    int n = JOptionPane.showOptionDialog(null, message,
            "title", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

    if (n == JOptionPane.OK_OPTION) {
        if (buttons[0].isSelected()) {
            return actions[0];
        }
        if (buttons[1].isSelected()) {
            return actions[1];
        } 
    } else {
            return null;
        }
}

1 Answers1

4

What happens if the condition in

if (n == JOptionPane.OK_OPTION) {

resolves to true and neither of the conditions in

if (buttons[0].isSelected()) {
    return actions[0];
}
if (buttons[1].isSelected()) {
    return actions[1];
} 

resolve to true? In that case, your method doesn't have a return statement. You need to return something in all execution paths.

Add a

return null;

or an appropriate return statement at the end of the method.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724