import javax.swing.JOptionPane;
public class Insurance {
final static String INPUT_GENDER = "Please enter your gender: (Male or Female)";
final static String MALE = "male";
final static String FEMALE = "female";
static String gender;
public static void main(String args[])
{
do
{
gender = JOptionPane.showInputDialog(INPUT_GENDER).toLowerCase();
System.out.println(gender);
}
while(!gender.equals(MALE) && !gender.equals(FEMALE));
}
}
The above piece of code is the beginning to a revision assignment, but I came across something I don’t understand. The user is asked to enter their gender, as “Male” or “Female”, and the program should only continue if the input satisfies one of these inputs. This is done by comparing the input to the final strings for MALE and FEMALE.
What I don’t understand is why it only works using && in the while statement. I expected it to need ||, because we want it to continue if the input matches either of the two gender strings. I understood that && should only allow the code to continue if both arguments are true.
TL;DR
while(!gender.equals(MALE) && !gender.equals(FEMALE)); //This works
while(!gender.equals(MALE) || !gender.equals(FEMALE)); //This does not work
while(gender.equals(MALE) || gender.equals(FEMALE)); //This does not work
&&is a logicalandoperator||is the logicaloroperatorUsing De Morgan, the following:
Can be translated to:
(note the additional parenthesis and the placement of the
!before them).Both the above mean that the
genderis neitherMALEorFEMALE.Your other code:
The above means –
genderis notMALEorgenderis notFEMALE.Similarly, the above means –
genderisMALEorgenderisFEMALE.