Home Java help translating printf syntax to print
Reply: 3

Java help translating printf syntax to print

Perfect Cookies
1#
Perfect Cookies Published in 2018-02-14 05:29:37Z

I'm trying to understand printf syntax. Specifically, I need to know what...

System.out.printf("%3s%12s%12s\n", "Sum", "Frequency", "Percentage"); 

...would translate to when using a print rather than printf statement.

Robby Cornelissen
2#
Robby Cornelissen Reply to 2018-02-14 05:48:20Z

That would be:

System.out.print("Sum   Frequency  Percentage\n");
//                --^-----------^-----------^
//                  3           12          12 positions, all right-aligned
Dheeraj Joshi
3#
Dheeraj Joshi Reply to 2018-02-14 05:54:18Z

In your question

System.out.print("Sum Frequency Percentage ") will do the work

Extra

While using printf statement you have to use format specifiers like System.out.printf("%3s%12s%12s\n", "Sum", "Frequency", "Percentage"); here%3s%12s%12s are format specifiers to help string formatting

In print statement System.out.print( "Sum", "Frequency", "Percentage"); you don't have to use any format specifiers here.

Ex:

system.out.print("The output is :"+output)

system.out.printf("The output is %d",output)

In printf statement the %d will be the place holder of integer output

Awanish
4#
Awanish Reply to 2018-02-14 05:55:32Z

printf is a convenience method to write a formatted string to this output stream using the specified format string and arguments.

Parameters:

format - A format string as described in Format string syntax

args - Arguments referenced by the format specifiers in the format string.

In your statement,

 System.out.printf("%3s%12s%12s\n", "Sum", "Frequency", "Percentage"); 

format - %s - indicates your format is a string

If you use "%s%s%s" - It indicates you are going to print 3 string arguments.

%3s%12s%12s indicates that you want to leave spaces before printing arguments

Hence your output would be

Sum Frequency Percentage

Trying printing these:

 System.out.printf("%3s%100s%12s\n", "Sum", "Frequency", "Percentage"); 

You would notice lot of space between first and second arguments

Try doing this:

 System.out.printf("%3s%10s\n", "Sum", "Frequency", "Percentage");

You notice that third string "Percentage" is not printed as you have mentioned only two "%s" in the format.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.41347 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO