I’m coding a class that’s supposed to model airplane cargo and I’m having trouble formatting the class’s toString() method. The following code:
public class Cargo
{
private String label;
private int weight, height, width, length;
public String toString()
{
return String.format("%s%s\t\t%-7s%-2s%-5d%-11s%-2s%-3d%-2s%-3d%-2s%d",
getLabel(), ":", "Weight", "=", getWeight(), "Dimensions",
"=", getHeight(), "X", getWidth(), "X", getLength());
}
public static void main(String[] args)
{
Cargo cargo1 = new Cargo("Bill's Beans", 1200, 20, 15, 30);
Cargo cargo6 = new Cargo("Chicago Bulls", 1000, 10, 10, 10);
Cargo cargo7 = new Cargo("Lots of Meat", 3000, 20, 20, 20);
Cargo cargo8 = new Cargo("Tammy's Tomatoes", 600, 6, 6, 6);
System.out.println(cargo1.toString());
System.out.println(cargo6.toString());
System.out.println(cargo7.toString());
System.out.println(cargo8.toString());
}
}
Produces this output:
Bill's Beans: Weight = 1200 Dimensions = 20 X 15 X 30
Chicago Bulls: Weight = 1000 Dimensions = 10 X 10 X 10
Lots of Meat: Weight = 3000 Dimensions = 20 X 20 X 20
Tammy's Tomatoes: Weight = 600 Dimensions = 6 X 6 X 6
As you can see, everything aligns well, except for “Tammy’s Tomatoes.” How can I fix this? Thanks.
It all aligns well except for “Tammy’s Tomatoes” because you’re using tabs.
In this case, your tabs are 4 characters long. While “Bill’s Beans:” is 13 characters, “Chicago Bulls:” is 14, and “Lots of Meat:” is 13, “Tammy’s Tomatoes:” is 17.
Or at least that’s what programmers think 😉
So when you put another tab on the last, one, it starts 4 characters after the rest.
You can fix this by adjusting the number of tabs depending on how many characters the names of the companies have.
Say that you want the dimensions to start at the 7th set of 4 spaces.
First, calculate the amount of spaces the names will occupy.
Divide by four (as I did above).
Subtract the number from 7.
So Tammy’s Tomatoes would be
7-4=3.Run a loop adding 3 “\t”‘s to the result (where you want to add them).
So in the end, your code would look like this:
EDIT to answer question in comment:
Well, you don’t really need to use
String.format(). You can actually just append the variables (for example,result + getWidth()). I just usedString.format()because that was what you had used. You could rewrite it to:Much simpler 🙂