驱动任务:编写程序输出信息实现右对齐。
解决方法:padRight(int n, String c)实现长度为n的字符串中,原字符串靠右放置,空余处用字符c补全。
//右对齐方法
public String padRight(int n, String c) {
if(n < this.str.length()){
System.out.println("新字符串长度n必须大于原字符串长度!");
return "ERROR";
}
else{
String newS;
newS = c.repeat(n - this.str.length());
return newS + this.str;
}
}
此方法需要重新写进String类中以方便在String类对象上直接使用,此时出现新的问题:
String类的实现是final的,意味着不能继承和修改它。
但是,你可以创建一个新的类,比如叫做"myString",这个类里封装一个String对象,然后在这个类中添加自定义的方法。这样就可以在这个类中实现自己想添加的任意方法,同时还可以使用String类中的所有方法。
// 自定义myString类
class myString {
private String str;
public myString(String str) {
this.str = str;
}
// 添加自己的方法
public String padRight(int n, String c) {
if(n < this.str.length()){
System.out.println("新字符串长度n必须大于原字符串长度!");
return "ERROR";
}
else{
String newS;
newS = c.repeat(n - this.str.length());
return newS + this.str;
}
}
}
此时即可创建并使用该类新方法,例如:
//测试
public class ttt {
public static void main(String[] args) {
myString ss = new myString("alien");
System.out.println(ss.padRight(12, " ") );
System.out.println(ss.padRight(12, "&") );
}
}
输出结果:
alien
&&&&&&&alien