1

I was wondering if you could do the following:

System.out.printf("%10.2f", car[i]);

Considering that I have redefined the toString() method.

public void toString() {
    return this.getPrice + "" + this.getBrandName;
}

Otherwise how do you format the price you print?

2 Answers 2

1

Since toString() returns a String, you can format the printed object with %s (see this) but not %f (see this).

You can get the price as a float and print the formatted number along with the brand:

class Car {
    public String toString() {
        return "I'm a car";
    }
    public double getPrice() {
        return 20000.223214;
    }
    public String getBrandName() {
        return "Brand";
    }
}
class Main {
    public static void main(String[] args) {
        Car c = new Car();
        System.out.printf("%10.2f %s", c.getPrice(), c.getBrandName());
    }
}

Output

  20000.22 Brand

(Represent the price in cents if it's easier.)

Sign up to request clarification or add additional context in comments.

Comments

0

Use String.format() instead.

public void toString() {
    return String.format("%10.2f", this.getPrice) + "" + this.getBrandName;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.