Java Printf帮助进行格式化

时间:2015-11-07 13:35:27

标签: java printf bluej

void catalog()
    {
        System.out.printf("\n%-5s%-5s%-15s%-15s%-6s%-15s%-5d\n",
            "Sno.","B.No.","BOOK-NAME","AUTHOR-NAME","COPIES","PUBLISHER","PRICE");
        for(int i=1;i<53;i++)
            System.out.print("-");
        System.out.println();
        for(int i=0;i<nob;i++)
            System.out.printf("%-5d%-5d%-15s%-15s%-5d%-10s%-10d\n",
                (i+1),bno[i],bname[i],author[i],availcopies[i],publisher[i],price[i]);
        for(int i=1;i<53;i++)
            System.out.print("-");
        System.out.println();
    }

我在java中使用printf有这个问题,所以这是我用printf

得到的错误
java.util.MissingFormatArgumentException: Format specifier '%-15s'
    at java.util.Formatter.format(Formatter.java:2519)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at Library.catalog(LibrarySystem.java:162)
    at LibrarySystem.main(LibrarySystem.java:218)

2 个答案:

答案 0 :(得分:0)

System.out.printf("\n%-5s%-5s%-15s%-15s%-6s%-15s%-5d\n",
    "Sno.","B.No.","BOOK-NAME","AUTHOR-NAME","COPIES","PUBLISHER","PRICE");

不起作用,因为最后一个是数字而你传递了字符串&#34; PRICE&#34;。

您应该为列名称使用不同的格式字符串。

列名:"\n%-5s%-5s%-15s%-15s%-6s%-15s%-5s\n"

答案 1 :(得分:0)

更改行

System.out.printf("\n%-5s%-5s%-15s%-15s%-6s%-15s%-5d\n",
            "Sno.","B.No.","BOOK-NAME","AUTHOR-NAME","COPIES","PUBLISHER","PRICE");

System.out.printf("\n%-5s%-5s%-15s%-15s%-6s%-15s%-5s\n",
            "Sno.","B.No.","BOOK-NAME","AUTHOR-NAME","COPIES","PUBLISHER","PRICE");

因为最后一部分% - 5d \ n“会尝试获取int值,但你想打印一个字符串,即”PRICE“

休息很好。

简单的错误