-2

Why my if-else statement doesn't execute when gender == "m" or gender == "f" ?

Scanner input = new Scanner(System.in);


    do 
    {
        System.out.print("Please enter 'm' for male and 'f' for female child: ");
        String gender = input.next();

        System.out.print("The height of the mother in inches: ");
        int motherHeight = input.nextInt();

        System.out.println("The height of the father in inches: ");
        int fatherHeight = input.nextInt();

        if(gender == "m") 
        {
            double childHeight = ((motherHeight * 13/12) + fatherHeight) / 2;
            System.out.println(childHeight);
        }
        else if (gender == "f")
        {
            double childHeight = ((fatherHeight * 13/14) + motherHeight) / 2;
            System.out.println(childHeight);
        }


    }

    while(input.hasNext());
Altaïr
  • 123
  • 2
  • 2
  • 9
  • You weren't paying attention in your Java 101 lectures :-) – Stephen C Jun 08 '14 at 03:01
  • @StephenC Hahaha Actually It's been while since I took the class so I forgot :D. – Altaïr Jun 08 '14 at 03:12
  • @StephenC I have another question. How can I get the program to keep allowing the user to enter new set of values until the user decides to exit ? – Altaïr Jun 08 '14 at 03:25
  • Your code already does that. The user simply has to enter ^D (Linux / Mac(?)) or ^Z (Windows) – Stephen C Jun 08 '14 at 03:35
  • No with my code I have to enter any character to keep the loop going. But what I want is after the program computes the `childHeight` immediately run the loop again. – Altaïr Jun 08 '14 at 03:46
  • I don't understand your comment. Have you tried a ^D / ^Z ??? – Stephen C Jun 08 '14 at 03:49
  • Thank you. I solved the issue. I just had to use `input.hasNextLine()` instead of using `input.hasNext()`. – Altaïr Jun 08 '14 at 06:16

1 Answers1

0

Use the right way to compare string because you are comparing memory location of the String

problem

if(gender == "m") //compares memory location of the String will return always false

solution

if(gender.equals("m")) 
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63