Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix a conditional which keeps going to the else statement rather than the if statement in java

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");
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading