字符串:Formatter类

本文通过一个具体的例子展示了如何使用 Java 中的 Formatter 类来进行字符串格式化。示例中的 Turtle 类利用 Formatter 对象来记录并显示海龟的位置变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



/*
 * 2018年3月30日15:28:34
 * 代码目的:
 *     演示Java中通过Formatter类进行字符串格式化的过程。
 *     Formatter的构造器经过重载可以接受多种输出目的地,最常用的还是控制台
 *     public static final PrintStream out = null; out为System类中定义的static final
 *    
 * */

//: strings/Turtle.java
import java.io.*;
import java.util.*;

public class Turtle {
  private String name;
  //私有成员Formater类对象,用它进行格式化
  private Formatter f;
  public Turtle(String name, Formatter f) {
    this.name = name;
    this.f = f;
  }
  public void move(int x, int y) {
	  //格式化,也可以通过调用System.out.printf()或者
	  //System.out.format()完成相同的功能。
    f.format("%s The Turtle is at (%d,%d)\n", name, x, y);
  }
  public static void main(String[] args) {
    PrintStream outAlias = System.out;
    Turtle tommy = new Turtle("Tommy",
      new Formatter(System.out));
    Turtle terry = new Turtle("Terry",
      new Formatter(outAlias));
    tommy.move(0,0);
    terry.move(4,8);
    tommy.move(3,4);
    terry.move(2,5);
    tommy.move(3,3);
    terry.move(3,3);
  }
} /* Output:
Tommy The Turtle is at (0,0)
Terry The Turtle is at (4,8)
Tommy The Turtle is at (3,4)
Terry The Turtle is at (2,5)
Tommy The Turtle is at (3,3)
Terry The Turtle is at (3,3)
*///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值