How to use System.out.printf

后端 未结 3 1663
太阳男子
太阳男子 2021-01-02 07:36

I tried to use printf but I have unexpected errors.

What is the fault on this code:

System.out.printf(\"The date is %d/%d/%d\", month,da         


        
相关标签:
3条回答
  • 2021-01-02 08:19

    Like C's sprintf, Strings may be formatted using the static method String.format:

       // 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's Birthday: %1$tm %1$te,%1$tY", c);
       // -> s == "Duke's Birthday: May 23, 1995"
    
    0 讨论(0)
  • 2021-01-02 08:28

    As per the Formatter docs, %d is a conversion for an integral value, which wouldn't work for doubles. You'll want to convert them to integers. Why would you represent month, day, and year as floating point numbers, anyway? You'd be much better off using a Date and using an appropriate formatter for date values.

    If you must use doubles for those values, you'll want %f instead of %d.

    0 讨论(0)
  • 2021-01-02 08:33

    Corrected code

     System.out.printf("The date is %f/%f/%f", month,day,year);
    
    0 讨论(0)
提交回复
热议问题