2012-07-26 103 views
0

可能重複:
Java String.equals versus ==JAVA if語句問題

我使用if語句在Java中,以確定天氣的人是通過詢問天氣男性或女性,他是個男孩或女孩。這是一個相當愚蠢的陳述,但我的問題是無論我輸入什麼,我總是得到「你是女性!」這很煩人。能否請你幫忙?這是代碼

import java.util.Scanner; 

class ifstatement { 

    public static void main(String args[]) { 
     System.out.print("please enter boy or girl as an input:"); 

     Scanner x = new Scanner(System.in); 
     String a = x.nextLine(); 

     if (a == "boy") { 
      System.out.print("You are a male"); 
     } 
     else { 
      System.out.print("You are a female!"); 
     } 
    } 
}  
+0

當你做一個'==「男孩」'要測試是否是*確切相同的實例*作爲字符串'「boy」',而不是字符串是否包含相同的字符。 – Thor84no 2012-07-26 18:18:32

回答

0

如果你說:

if ("boy".equals(a)){ 
System.out.print("You are a male"); 
} else if ("girl".equals(a)){ 
System.out.print("you are a female!"); 
{ else { 
System.out.print("invalid response!"); 
} 

這將解決您的問題。處理字符串時,應始終使用.equals()來比較確切的值。 「==」運算符通常比較兩個對象是否指向內存中的相同位置。由於一個字符串是一個對象,它們是不一樣的。

+0

非常感謝!你的回答是最有幫助的 – 2012-07-26 18:27:44

4

使用equals()方法來比較String

equals()對象

==比較比較引用重視

使用

if ("boy".equals(a)) { 

此Wi LL比較字符串的"boy"實例與由a


稱爲String實例見

+2

和equalsIgnoreCase()如果你不關心這種情況。 – cjstehno 2012-07-26 18:18:31

+0

我無法理解。你會寫出那行代碼嗎? – 2012-07-26 18:23:19

+0

檢查udpate 2012-07-26 18:26:07

0

==比較使用對象引用,兩個對象是否指向同一個存儲位置。 .equals()在Object類中的作用相同,但是,String類會覆蓋它以執行值比較。

0

==運算符檢查對象的引用是否相等。當測試字符串相等時,這是不夠的。一種引用相等測試在String.equals() method內完成,其他檢查項目之中:

public boolean equals(Object anObject) { 
     if (this == anObject) {  // Reference equality 
      return true; 
     } 
     if (anObject instanceof String) { 
      String anotherString = (String)anObject; 
      int n = count; 
      if (n == anotherString.count) { // Are the strings the same size? 
       char v1[] = value; 
       char v2[] = anotherString.value; 
       int i = offset; 
       int j = anotherString.offset; 
       while (n-- != 0) { 
        if (v1[i++] != v2[j++])  // Compare each character 
         return false; 
       } 
       return true; 
      } 
     } 
     return false; 
    } 
0

1.使用.equals()方法比較java對象,Strings是Java中的對象。

2.使用a.equals("boys")而且會給你正確答案 ....