Reputation: 159
I have a toString()
method from my class that takes the information from the object and puts it into a string to be printed.
This is what it should look like:
Susan 70 <Average C
Alexander 80 >Average B
, but I'm having trouble formatting my toString()
method. This is what it looks like this right now which is very unorganized.
public String toString() {
return ("\n" + fullName +
" " + relativeScore +
" " + testScore);
}
I would normally use printf, but since it's a return statement I can't use it. Any help would be much appreciated.
Upvotes: 2
Views: 7233
Reputation: 3326
you're doing it wrong way. Susan is 5 letter word and Alexander is 9 letter word. So if susan is followed by 10 white spaces then alexander should be followed by 10-9+5= 6 white spaces. You should consider the length of fullname in your code.
Upvotes: 0
Reputation: 347314
Depending on what you want to achieve, you could simply use String#format
, for example:
System.out.println(String.format("%-10s %d %10s %5s", "Susan", 70, "<Average", "C"));
Which outputs
Susan 70 <Average C
For more details have a look at this example and Formatter
Upvotes: 3
Reputation: 3688
String.format
method returns a new String object, so you can use it rather than printf
, for instance:
public String toString() {
return String.format("%s\t%3d\t%s", fullName, relativeScore, testScore);
}
Upvotes: 1
Reputation: 14438
You could use String.format()
and do it just like you would do with printf()
return String.format("whatever comes here");
Upvotes: 0