緣涞の沩倪 緣涞の沩倪
走自己的路,让别人去说吧!
关注数: 49 粉丝数: 142 发帖数: 8,864 关注贴吧数: 20
有大神没,帮忙看看这程序嘛 看不懂了 新人... 如题 代码如下,书上的: // 通过提供一个具有 name 属性的简单类来使用 Formattable 接口,它支持控制输出的宽度和对齐方式 import java.util.Locale; import java.util.Formatter; import java.util.Formattable; public class TestFormattable implements Formattable{ String name; public TestFormattable(String name) { this.name = name; } public void formatTo(Formatter fmt,int f,int width,int precision) { // 实现 formatTo 方法 StringBuilder sb = new StringBuilder(); if(precision == null) { sb.append(name); } else if(name.length()<precision) { sb.append(name); } else { sb.append(name.substring(0,precision - 1)).append('*'); } // 使用宽度参数来进行调整 if((width != null)&&(sb.length()<width)) { for(int i=0,n=sb.length();i<width-n;i++) { if((f&Formattable.LEFT_JUSTIFY)==Formattable.LEFT_JUSTIFY) { sb.append(''); } else { sb.insert(0,''); } } } fmt.format(sb.toString()); } public static void main(String[] args) { TestFormattable my1=new TestFormattable("John"); TestFormattable my2=new TestFormattable("Really Long Name"); // 使用 toString() 方法 System.out.println("First Object: "+my1); // 其次使用 Formatter 类 System.out.format("First Object: '%s'\\n", my1); // 使用 Formatter 类 System.out.format("Second Object: '%s'\\n", my2); // 使用带宽度的 Formatter 类 System.out.format("Second Object: '%10.5s'\\n", my2); // 使用带宽度和左边对齐的 Formatter 类 System.out.format("Second Object: '%-10.5s'\\n",my2); }}
1 下一页