2014-10-30 31 views
0

我正在完成我的大學作業,並且遇到了此問題。我需要完成的是當用戶輸入鋅,鐵,鋁和鈉的金屬元素時,我希望程序返回真實狀態。當比較的元素爲真時,布爾值仍然輸出false。你能否在這段代碼中找出問題?無法在布爾值上返回真實值

IonicCompound

public class IonicCompound { 

    public static void main(String args[]) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Please enter a metallic element: "); 
     String element1 = input.nextLine(); 
     System.out.println("Please enter a non-metallic element: "); 
     String element2 = input.nextLine(); 
     Elements element = new Elements(element1, element2); 
     element.isMetal(element.first); 
     if (element.isMetal(element.first) == true) { 
      System.out.println("It's a metallic element "); 
     } else { 
      System.out.println("It's not a metallic element "); 
     } 
    } 
} 

Elements

public class Elements { 

    public String first, second; 

    public Elements(String f, String s) { 
     first = f; 
     second = s; 
    } 

    public boolean isMetal(String ff) { 
     if (ff == "iron" || ff == "Iron" || ff == "aluminium" || ff == "Aluminium" || ff == "sodium" || ff == "Sodium" || ff == "zinc" || ff == "Zinc") { 
      return isMetal(ff) == true; 
     } else { 
      return false; 
     } 
    } 

    public String toString() { 
     String element = first + " " + second; 
     return element; 
    } 
+2

不要用'比較字符串=='。請參閱:[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839) – Jesper 2014-10-30 21:09:03

回答

2

你調用從內isMetalisMetal,所以你無限遞歸。我想你想要的只是return true;

另外,看看功能String.equals==運算符可能沒有達到您期望的Java效果。

2

比較字符串使用String API equals方法。下面是可以在你的代碼中應用的例子:

ff.equals("iron") // This compares if String contain the same series of characters 

ff=="iron" // this compares if the memory address of the ff variable is "iron" 
+0

非常感謝。等於是問題,現在它完美地工作。 – totovic 2014-10-30 21:13:41

+0

請使用equalsIgnoreCase()來確保它對「鐵」和「鐵」返回true。 – WarrenFaith 2014-10-30 21:17:55

1

使用.equals()比較對象時,而不是==(字符串是對象)。 ==將比較對象的引用,而.equals()將檢查它們是否具有相同的值。由於兩個對象很少有相同的引用,因此除了比較基本類型(int,char,但String不是基本類型!)之外,不應該使用==

所以,你要

ff.equals(iron)