2012-11-24 43 views
0

我得到這個代碼:輸入從nextLine閱讀不等於字符串值

System.out.println("Enter the brand and cash value"); 

    String brand = keyboard.nextLine(); 

    long cash = keyboard.nextDouble(); 
    String buffer = keyboard.nextLine(); 

,但即使我進入我想比較確切的字符串值,它沒有認識到它們是相同的。奇怪的是,當我進入這個:

compare[0] = new Car ("BMW", 12.00);

,而不是這樣的:

compare[0] = new Car (brand, 12.00);

它的工作原理

我也用等於:

public boolean equals(Car other) 
{ 
    if (other == null) 
    { 
     return false; 
    } 

    if(this.brand == other.brand && this.cash == other.cash) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+2

您是否使用.equals()方法檢查相等性? ==在這裏不起作用 –

+0

在進行比較之前,打印出您正在比較的兩個字符串。這應該可以幫助您查看是否有任何差異。另外,不要使用'=='來比較字符串(如前所述)。 –

+0

我使用等於我重新定義了它 –

回答

2

您正在使用==至測試字符串相等,而"BMW"是一個字符串字面值,它在一個池中被執行,而brand不是。換句話說,如果您有:

String s1 = "BMW"; 
String s2 = "BMW"; 
String s3 = getString(); //receives "BMW" from the scanner 

s1 == s2是真的
s1 == s3是假
s2 == s3是假
s1.equals(s2)是真的
s1.equals(s3)是真的
s2.equals(s3)是真的

底線:您應該使用equals來比較字符串。

你可以在this post瞭解更多關於它的信息。

編輯

在你equals方法,你需要改變

if(this.brand == other.brand && this.cash == other.cash) 

此代碼:

if(this.brand.equals(other.brand) && this.cash == other.cash) 

還要注意有一些其他問題,您equals - 特別是,它不會覆蓋等於:它應該是public boolean equals(Object o)

EDIT 2

你可以實現你的equals方法是這樣的例子(它假設品牌不能爲空 - 如果沒有你需要處理特定情況下也如此)

@Override 
public boolean equals(Object obj) { 
    if (obj == null || getClass() != obj.getClass()) { 
     return false; 
    } 

    final Car other = (Car) obj; 
    return (this.cash == other.cash && this.brand.equals(other.brand)); 
} 

請注意,您還應該覆蓋hashcode方法。正如我在下面所示

public boolean equals(Car other) 
{ 
    if (other == null) 
    { 
     return false; 
    } 

    if(this.brand.equals(other.brand) && this.cash.equals(other.cash)) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+0

我使用equals()這可能不是問題 –

+0

@GladstoneAsder我知道你在你的Book類中覆蓋了'equals'。你可以顯示該代碼嗎?我可以想象,在「equals」方法中,您將品牌與「if(this.brand == other.brand){}'進行比較。 – assylias

+0

我真的不知道什麼是錯的 –

0

使用java.lang.Object的平等法==用於檢查r字符串的參考及其值。

在這種情況下,您的值是相同的,但不是參考。

因此,您需要使用equals,因爲它僅用於檢查值。
這就是你想要做的,我猜。

+1

this.cash.equals(other.cash)在這裏是錯誤的。 – vels4j

+0

它工作,即使我把等於現金 –

+0

@ vels4j這取決於如果現金是一個'雙'或'雙'。它似乎是一個「雙」,但在這種情況下,「等於」東西不會真正編譯。 – assylias

1

您需要使用

this.brand.equals(other.brand)

if條款,而不是

this.brand == other.brand 

的的