PDA

View Full Version : formatting data in java


daniel_g
09-22-2006, 02:23 AM
In java, I know it's possible to format words or numbers. An example would be

System.out.printf("%15s\n", word);

Which would format whatever the value of word in a space with size 15.

Somewhere I read it's possible to do the same if you are returning a value, but did not provide any examples of it. I tried:

return %15s\n,word;
//ovbiusly I'm trying to return "word", can I format it while I return it?

That doesn't work, as I get illegal start of expression as an error.

Any ideas?

daniel_g
09-22-2006, 05:13 AM
Meh, I figured it out.
Instead of writting

return name;

We write

System.out.printf("%-7s", name);

And that automatically returns the formated value.

Aradon
09-22-2006, 06:00 PM
Meh, I figured it out.
Instead of writting

return name;

We write

System.out.printf("%-7s", name);

And that automatically returns the formated value.

Not exactly. It doesn't "return" it at all, it just sends it to the out stream using printf...

If you really needed to format a string you could do so through the string
utilities. For example, substring should be able to cut off the part of the string you want.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#substring(int,%20int)

This means however that you will have to check to see if the string is too short. If you don't you'll get an outofbounds exception. So just check the length, if it's less then what you want to crop it to, just return it, else, crop it with substring and return it.

Easy peasy, japanesey

daniel_g
09-23-2006, 03:28 AM
Oh, so that explains why I have to type return " "; at the end of the method.

"Cool, now I can have more fun with strings".substring(21, 29)
Hehe :)