How do I set the fields with with a variable and not a constant? This is what I want:
Here x is an integer variable.System.out.printf("%xs\tPlayer Points\tComputer Points\t Winner\n", "Name");
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
How do I set the fields with with a variable and not a constant? This is what I want:
Here x is an integer variable.System.out.printf("%xs\tPlayer Points\tComputer Points\t Winner\n", "Name");
You could create the format string as, itself, a formatted string!
int x = 42; String fmt = String.format("%%%ds\tPlayer Points\tComputer Points\t Winner\n", x); System.out.printf(fmt, "Name");
Notice how %% is used to represent a literal % character in the format. Details in the Formatter API docs.
-----
The width argument allows an alternative to your use of the \t character whose exact behaviour may or may not be what you want or expect. In particular it may not do the same thing in all circumstances (console, text component, web page etc).
Also the %n specifier provides an alternative to the \n character and will do the right thing to produce a newline whatever the OS.
ranjithfs1 (March 18th, 2012)
That was helpful! Thanks! :-)
You're welcome.