2014-06-08 135 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

訣竅在於條件。 –