How to use System.out.printf

I tried using printf , but I got unexpected errors.

What is the error in this code:

 System.out.printf("The date is %d/%d/%d", month,day,year); 

I want to print the date and month , day and year are double variables.

+7
source share
3 answers

According to the docs, Formatter %d is a conversion for an integer value that won't work for doubles. You will want to convert them to integers. Why would you present month, day, and year as floating point numbers? You will be much better off using Date and using the appropriate formatter for the date values.

If you use double values ​​for these values, you need %f instead of %d .

+15
source

Like C sprintf, strings can be formatted using the static String.format method:

  // Format a string containing a date. import java.util.Calendar; import java.util.GregorianCalendar; import static java.util.Calendar.*; Calendar c = new GregorianCalendar(1995, MAY, 23); String s = String.format("Duke Birthday: %1$tm %1$te,%1$tY", c); // -> s == "Duke Birthday: May 23, 1995" 
0
source

Fixed code

  System.out.printf("The date is %f/%f/%f", month,day,year); 
-2
source

All Articles