我写了以下toString()方法
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "
+ (this.sale == null) ? "Not on sale" : + this.sale.toString();
}
但是我使用if语句的方式存在问题。
eclipse: "cannot covert from string to boolean"
答案 0 :(得分:2)
连接运算符+
的平衡存在问题。另外,我编辑了您的方法如下:
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "+ ((this.sale == null) ? "Not on sale" : this.sale.toString());
}
当您编写IF-ELSE短手时,请尝试将所有内容保存在(...)
括号中,以便轻松跟踪事物。我不关心其他专业人士对此的看法,但如果这有助于你理解事情,那就这样吧!
答案 1 :(得分:1)
这是非法语法
(this.sale == null) ? "Not on sale" : + this.sale.toString()
并且编译错误应该提醒您这个问题。
相反,请使用
((this.sale == null) ? "Not on sale" : this.sale.toString())
我已将整个ternary operator放入括号中以明确。