user7805755
user7805755

Reputation:

I'm using toString method, but it doesn't give me the format I want?

I want my method to return a rectangle base(coordinates) height and width.

An example

For the rectangle with a lower left corner located at (-3, 2) and having a width of 4 and a height of 5, the method should return exactly “base: (-3,2) w:4 h:5”. For this example, there is a single space at location 5, 12, and 16.

//left = x, bottom =y , width = w, height = h

this is the method I have

public String toString(){
    return String.format("%-5s%-12s%16d","base:" ,"(",this.left,",", this.bottom,")", "w:",this.width, "h:",this.height);
}

Upvotes: 0

Views: 72

Answers (3)

Sillas Camara
Sillas Camara

Reputation: 76

The easiest way to do this function is to put all the text you want to display in the first parameter of String.format().

Like this:

public String toString(){
        return String.format("base:(%d,%d) w:%d h:%d", this.left, this.bottom, this.width, this.height);
}

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347314

There is a coalition between the number of format specifiers and the number of parameters, they should be equal in quality.

Something like String.format("%-5s(%d, %d) w:%d h:%d","base:", left, bottom, width, height) will print base:(-3, 2) w:4 h:5 ... based on the values you have provided

The format specifiers are based on C, have a look at these examples for more details

Upvotes: 1

guest
guest

Reputation: 6708

I don't understand why you're interpolating several constant strings into a constant format string. Could you confirm that that's what you really want?

Also, I count several more arguments passed to String.format than there are format specifiers. Get that sorted out first. By then, it should be clearer why the output you're getting isn't matching what you want.

Upvotes: 0

Related Questions