我试图使用一些新的Java字符串格式化技巧,非常基本的东西。它编译时没有任何错误消息,但不允许我执行代码。有人可以向我解释为什么这是错的吗?提前谢谢。
我的代码:
class TestingStringFormat {
public static void main(String args[]) {
System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120);
for(int i=0; i<20; i++){
System.out.printf("%-2d: ", i, "some text here/n", 1);
}
}
}
答案 0 :(得分:2)
在两个printf
中,格式说明符的数量与您传入的参数数量不匹配。
例如,第一个printf
读取:
System.out.printf("Total cost %-10d ; quantity %d\n", "ten spaces",5, 120);
期望一个整数后跟另一个整数。您传递的是String
,int
和另一个int
。
在你的第二个printf
:
System.out.printf("%-2d: ", i, "some text here/n", 1);
期待一个整数。您传递的是int
,String
和另一个int
。
答案 1 :(得分:1)
您错过了与String
方法中第一个printf
参数对应的格式说明符,因此会抛出IllegalFormatConversionException
System.out.printf("Total cost %s %-10d ; quantity %d\n", "ten spaces", 5, 120);
^
您的第二个printf
语句不会抛出运行时异常,但只会显示第一个参数。你可以做到
System.out.printf("%-2d: %s %d%n", i, "some text here/n", 1);
阅读:Formatter