我正在完成我的大學作業,並且遇到了此問題。我需要完成的是當用戶輸入鋅,鐵,鋁和鈉的金屬元素時,我希望程序返回真實狀態。當比較的元素爲真時,布爾值仍然輸出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;
}
不要用'比較字符串=='。請參閱:[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839) – Jesper 2014-10-30 21:09:03