我在类中实现Formattable接口的formatTo()方法。然后,我在printf()参数中使用它,如下所示:
public static void main(String[] args)
{
BankAccount1 bankAccount = new BankAccount1(1234.12) ;
//Don't understand this code
System.out.printf("%s %10S.\n", "Balance = ", bankAccount) ;
}
class BankAccount implements Formattable
{
public void formatTo(Formatter formatter, int flags, int width, int precision)
{
Appendable appendable = formatter.out() ;
String balanceString = "" + balance ;
for (int i = balanceString.length() ; i < width ; i++)
balanceString = "$" + balanceString ;
try {
//tells appendable to append balanceString to printf's string
appendable.append(balanceString) ;
}
catch (IOException e) {
System.exit(0) ;
}
}
}产出如下:
Balance = $$$1234.12.我的问题是,在这个问题上:
System.out.printf("%s %10S.\n", "Balance = ", bankAccount) ;我知道%s代表字符串,但是"%10S.\n“在做什么呢?此外,在“%10.\n”中,为什么“%10”-为什么是大写S -它代表什么?
发布于 2016-02-29 15:06:00
在这里,BankAccount Class实现了Formattable interface,
现在,
printf的语法看起来也是这样,
%[argument_index$][flags][width][.precision]conversion现在,让我详细说明一下,
%10表示输出的总width为10. (in java, string length = 10)。
对于S或S的意思来说,
如果参数arg为空,则结果为" null“。如果arg实现了Formattable,那么将调用arg.formatTo。否则,将通过调用arg.toString()获得结果。
最后由.完成,它将反映到输出。(点)
最后,输出:10长度的$$$1234.12. ($$$1234.12),圆点结束.
这里,有趣的是S-它将调用formatTo of BankAccount,正如我前面提到的。
https://stackoverflow.com/questions/35702529
复制相似问题