I want to have the user to select either one of the choices. but my code doesnt work. not sure if i got it wrong

if (!jRadioMale.isSelected() || !jRadioFemale.isSelected()) {
  JOptionPane.showConfirmDialog(rootPane, 
      "Please Select Male or Female", 
      "", 
      JOptionPane.OK_CANCEL_OPTION);
} else {
  // Continue to next
}   

it keeps prompting "Please select male or female" even if one is selected!

有帮助吗?

解决方案

You need to do this ...

 if(jRadioMale.isSelected() || jRadioFemale.isSelected()){
    //Continue to next           

            }
    else{
     JOptionPane.showConfirmDialog(rootPane, "Please Select Male or Female", "", JOptionPane.OK_CANCEL_OPTION);

    }   

Your code will always show the alert because Your condition returns true if any one of the button is not selected

其他提示

Instead of OR (will keep prompting, because when one is selected the other IS NOT)

if (!jRadioMale.isSelected() || !jRadioFemale.isSelected()) {

you really want AND (when either is selected)

if (!jRadioMale.isSelected() && !jRadioFemale.isSelected()) {

or you could use the negation of the AND

if (!(jRadioMale.isSelected() || jRadioFemale.isSelected())) {
   if (!jRadioMale.isSelected() && !jRadioFemale.isSelected()) {
  JOptionPane.showConfirmDialog(rootPane, 
      "Please Select Male or Female", 
      "", 
      JOptionPane.OK_CANCEL_OPTION);
} else {
  // Continue to next
}   

Use AND instead of OR

I agree with @Elliott Frisch. The problem is in the following code:

!jRadioMale.isSelected() || !jRadioFemale.isSelected()

For this expression, two situations will satisfy: 1.User has selected no radio. 2.User has selected only one radio. In this case, !jRadioMale.isSelected() or !jRadioFemale.isSelected() will be satisfied, which make the total expression is true.

I think you may want to the expression is true only under situation 1. You can modified your code as following: !jRadioMale.isSelected() && !jRadioFemale.isSelected()

Wish my answer may give you some help.

I am afraid you need to get rid of ! , so it will works

    if(jRadioMale.isSelected()|| jRadioFemale.isSelected()){                       
                }else{
 JOptionPane.showConfirmDialog(rootPane, "Please Select Male or Female", "", JOptionPane.OK_CANCEL_OPTION);



}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top