user5493178
user5493178

Reputation:

How do i use the printf command with more than one string and arg?

I have written a object that creates a rectangle in java (eclipse), but when i try to print out the information about the rectangle I get a wired error.

This works fine, but is not to pleasant to lock at, since it returns a value with 14 digits after ","

System.out.println("Rectangle2\t Width: " + rectangle2.width + "\tHeight: " + 
            rectangle2.height + "\tArea: " + rectangle2.getArea() + "\tPerimiter: " + rectangle2.getPerimiter());

While this prints it with two digits after ",", which is what I'm trying to accomplish. But it only prints the first string and number and results in an error.

    System.out.printf("Rectangle2\t Width: %.2f%n", rectangle2.width, "\tHeight: %.2f%n", 
            rectangle2.height + "\tArea: %.2f%n", rectangle2.getArea() + "\tPerimiter: %.2f%n", rectangle2.getPerimiter());

If i only use "," instead of "+" the error don't come up, but it still only prints the first string and number. How do I print it with %.2f%n without most of it disappearing?

Upvotes: 1

Views: 74

Answers (1)

neomega
neomega

Reputation: 732

The first parameter of printf is the format String and all the other parameters are the arguments to format the String.

System.out.printf("Rectangle2\t Width: %.2f%n\tHeight: %.2f%n\tArea: %.2f%n\tPerimiter: %.2f%n", rectangle2.width,rectangle2.height, rectangle2.getArea(),rectangle2.getPerimiter());

Upvotes: 3

Related Questions