-3

I have write the following toString() methode

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();
}

But there is a problem with the way I use the if statement.

eclipse: "cannot covert from string to boolean"
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
GuyChabra
  • 105
  • 1
  • 3
  • 12

2 Answers2

2

You had an issue with the balancing of concatenation operator +. Also, I edited your method to be the following:

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());
}

When you are writing IF-ELSE short hand, try to keep everything in a (...) set of parentheses to keep track of things easily. I don't care what other professionals say about this, but if this helps you to understand things, so be it!

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
1

This is illegal syntax

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

and a compilation error should have alerted you to this problem.

Instead, use

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

I've placed the entire ternary operator into parentheses to be clear.

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108