gpt4 book ai didi

Java Formattable Interface 和 printf 参数

转载 作者:行者123 更新时间:2023-12-01 10:19:29 25 4
gpt4 key购买 nike

我正在类中实现 Formattable 接口(interface)的 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”在做什么?而且在“%10S”中。\n“为什么“%10S”为什么要大写S,它代表什么?

最佳答案

这里,BankAccount Class 实现了 Formattable 接口(interface)

现在,

Syntax of printf looks likewise,

%[argument_index$][flags][width][.precision]conversion

现在,让我详细说明一下,

%10 表示输出的总宽度将为10。(在java中,字符串长度= 10)

现在 S 或 s 的意思是,

If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

最后以.结尾,这将反射(reflect)到输出中。(点)

最后,输出:$$$1234.12.,长度为10($$$1234.12),以点结尾。

这里,有趣的是 S -它将调用 BankAccount 的 formatTo,正如我上面提到的。

关于Java Formattable Interface 和 printf 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35702529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com