作为 toString() 实现的一部分评估 "IF ELSE" shorthand

Evaluating "IF ELSE" shorthand as part of a toString() Implementation

我写了下面的 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"

您在平衡连接运算符 + 时遇到了问题。此外,我将您的方法编辑为以下内容:

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 速记时,请尽量将所有内容放在 (...) 组括号中以便于跟踪。我不在乎其他专业人士对此怎么说,但如果这有助于您理解事物,那就这样吧!

这是非法语法

(this.sale == null) ? "Not on sale" : + this.sale.toString()

编译错误应该提醒您注意这个问题。

改为使用

((this.sale == null) ? "Not on sale" : this.sale.toString())

为了清楚起见,我将整个 ternary operator 放在括号中。