Home > database >  How to fix a conditional which keeps going to the else statement rather than the if statement in jav
How to fix a conditional which keeps going to the else statement rather than the if statement in jav

Time:08-25

So I am newbie for Java and I was trying something and it wont work, I am trying to get input from the user for only male or female and the code build but whenever I enter the input M or F it automatically gives the else "You did not choose M or F"

        char gender = readertext.next().charAt(0);
        char M = 0;
        char F = 0;
        if (gender == M) {
            M = 1;
            System.out.println("You picked M");
        } else if (gender == F) {
            F = 1;
            System.out.println("You picked F");
        } else {
            System.out.println("You did not choose M or F");
        }

CodePudding user response:

char gender = readertext.next().charAt(0);
if (gender == 'M') {
  System.out.println("You picked M");
} else if (gender == 'F') {
  System.out.println("You picked F");
} else {
  System.out.println("You did not choose M or F");
}
  • Related