java - 使用S格式打印实现Formattable的类

标签 java interface

我正在自学 Java,并开始使用接口(interface)。我正在使用 Cay Horstmann 编写的一本名为《Big Java Early Objects》的教科书。我遇到了一个对我来说相当难以理解的练习。该练习指出:

System.out.printf 方法具有用于打印整数、 float 的预定义格式 数字和其他数据类型。但它也是可扩展的。如果您使用 S 格式, 可以打印任何实现 Formattable 接口(interface)的类。该接口(interface)有一个 单一方法:

    void formatTo(Formatter formatter, int flags, int width, int precision)

在本练习中,您应该使 BankAccount 类实现 Formattable 接口(interface)。 忽略标志和精度,并使用给定的宽度简单地格式化银行余额。 为了完成此任务,您需要获取如下的 Appendable 引用:

    Appendable a = formatter.out();

Appendable 是另一个带有方法的接口(interface)

    void append(CharSequence sequence)

CharSequence 是另一个由 String(以及其他)实现的接口(interface) 类(class)。构造一个字符串,首先将银行余额转换为字符串,然后 用空格填充它,使其具有所需的宽度。将该字符串传递给追加方法。

我已经到了这样的地步:在一个测试类中,我创建了一个包含 1500 美元的 BankAccount 对象的实例。调用 System.out.printf("%s", account) 给我 1500。但是,我应该获取宽度参数来添加填充,但我不知道如何实现这一点。

此外,我拥有的代码对我来说没有意义。我按照练习的描述编写了代码,但我不知道它是如何工作的。

 public class BankAccount implements Formattable
 {  
    private String name;
    private double balance;

    /**
       Constructs a bank account with a zero balance.
    */
    public BankAccount()
    {   
        this.name = "";
        this.balance = 0;
    }

    /**
        Constructs a bank account with a given balance.
        @param initialBalance the initial balance
     */
    public BankAccount(String name, double initialBalance)
    {   
        this.name = name;
        this.balance = initialBalance;
    }

    /**
        Deposits money into the bank account.
        @param amount the amount to deposit
     */
    public void deposit(double amount)
    {  
        balance = balance + amount;
    }

    /**
        Withdraws money from the bank account.
        @param amount the amount to withdraw
     */
    public void withdraw(double amount)
    {   
        balance = balance - amount;
    }

    /**
        Gets the current balance of the bank account.
        @return the current balance
     */
    public double getBalance()
    {   
        return balance;
    }

    public String getName()
    {
        return this.name;
    }

    public void formatTo(Formatter formatter, int flags, int width, int precision)
    {
        Appendable a = formatter.out();

        String padding = "";
        for(int i = 0; i < width; i++)
        {
            padding = padding.concat(" ");
        }

        String bankBalance = padding + String.valueOf(getBalance());

        try
        {
            a.append(bankBalance);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

上面是我的 BankAccount 类,它实现了 Formattable 并定义了 formatTo 方法。我不明白 Appendable a = formatter.out 的作用。对 a.append(bankBalance) 的调用如何允许我在我的测试器类中使用 System.out.printf(%s, account);

下面是我的测试人员类(class)。

public class FormatTester
{
    public static void main(String[] args)
    {
        BankAccount account = new BankAccount("Bob Robert", 1500);

        System.out.printf("%s", account);
    }
}

这将打印 1500,没有任何填充。我知道没有填充,因为宽度参数没有给出 int 值。我不知道如何设置它,因为如果我尝试这样做:

public class FormatTester
{
    public static void main(String[] args)
    {
        BankAccount account = new BankAccount("Robert Bob", 1500);

        Formatter formatter = new Formatter();

        System.out.printf("%s", account.formatTo(formatter, 0, 5, 0);
    }
}

它提示说

The method printf(String, Object...) in the type PrintStream is not applicable for the arguments (String, void)

如果我不能这样设置宽度,我该怎么做呢?顺便说一句,名字并不重要。我试图格式化名称,但决定暂时保留余额。

最佳答案

请解释一下...

 Formatter fmt = new Formatter();
   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
                                "Fruit Titanesque, Inc.");
   fmt.format("%s", sn);                   //   -> "Huge Fruit, Inc."
   fmt.format("%s", sn.toString());        //   -> "HUGE - Huge Fruit, Inc."
   fmt.format("%#s", sn);                  //   -> "HUGE"
   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."

以及documentation .

关于java - 使用S格式打印实现Formattable的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528094/

相关文章:

java - Java 中的接口(interface) : cannot make implemented methods protected or private

c# - 如何设置具有多个值以及单个 w/custom 属性的 ExportMetaData?

android - 继承静态方法和字段

java - 为什么我的包裹对象返回为空?安卓开发

java - 如何在android中的sqlite数据库中存储html页面

java - 在Java中的BrowserMob中仅获取POST请求/响应

c# - .net 中的访问控制列表 (ACL) 抽象层

java - 如何在 JUnit 测试类中运行(或更改顺序)特定测试方法?

java - 使用 JDK8 Stream 如何迭代嵌套对象

java - 我可以使用接口(interface)作为枚举中的变量吗?