2014-06-08 219 views
-2

为什么我的if-else语句在gender == "m"gender == "f"?时不执行?if-else语句在Java中不执行

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()); 
+0

比较字符串在你的注意力中Java 101讲座:-) –

+0

@StephenC哈哈哈其实自从我上课之后,我就忘记了:D。 –

+0

@StephenC我还有一个问题。我怎样才能使程序继续允许用户输入新的一组值,直到用户决定退出? –

回答

0

使用正确的方法,因为你是你不是比较字符串的内存位置

问题

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

解决方案

if(gender.equals("m")) 
+0

谢谢。我有另一个问题。我怎样才能使程序继续允许用户输入新的一组值,直到用户决定退出? –

+0

@ user3716773把它放在while循环中 –

+0

诀窍在于条件。 –