简体   繁体   中英

IllegalFormatConversionException d != java.lang.Integer when trying to printf date?

public void display() {
    System.out.printf("%-10d%-12s%-12s%10.2f%8d%12.2f%1$td.%1$tm.%1$ty %n\n",
    this.getID(),
    this.getFirstName(),
    this.getLastName(),
    this.getState(),
    this.getNo(),
    this.getAmt(),
    this.getDate());
}

Is my method for printing out some of my info. this.getDate returns date as a Date (java.util.Date) type.

I had an example given to me as System.out.printf("%1$td.%1$tm.%1$ty %n", date); to print out the data in a dd.mm.yyyy format. I tried to place that into my code, but by the looks of things I made a formatting mistake?

I've been trying a few printing methods now but find it confusing how it would work on its own but then I have issues when I try to place it into a larger printf statement.

The issue is that the number before the $-sign indicates the absolute index (starting with 1! 😉) of the Object. You intended to point at the Date (Index 7) but pointed at the first element instead, which happend to be an Integer. You'll want to use "%-10d%-12s%-12s%10.2f%8d%12.2f%7$td.%7$tm.%7$ty %n\\n" for formatting.

First of all Date formatting is a complex issue and is already dealt with for you. So you trying to come up your own formatter (such as "%-10d%-12s%-12s%10.2f%8d%12.2f%td.%toString() of class Date . If you need better formatting than look at method DateFormat.format(Date date) . However, note that if you use Java 8 or higher than the class java.util.Date shouldn't be used. Look at java.time package. Use ZonedDateTime or any of its "brothers" instead of Date and use DateTimeFormatter to format it to string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM