📄 account.java
字号:
/**
*
*/
package StringAlign;
/**
* @author Owner
*
*/
public class account {
public static final int JUST_LEFT = 0; //左对齐
public static final int JUST_RIGHT = 2; //右对齐
public static final int JUST_CENTER = 1; //居中对齐
private int just; //当前对齐格式
private int maxChars; //一行的最大长度
/** */
/** 默认构造函数 */
public account() {
//默认为居中对齐,一行的最大长度为80
this.just = JUST_CENTER;
this.maxChars = 80;
}
/** */
/** 构造一个字符串对齐器,需要传入一行的最大长度和对齐的格式 */
public account(int maxChars, int just) {
this(); //首先构造一个默认字符串对其器
//根据传入参数修改字符串对齐器的属性
this.setJust(just);
this.setMaxChars(maxChars);
}
public int getJust() {
return just;
}
/** */
/** 设置字符串对齐器的对齐格式 */
public void setJust(int just) {
switch (just) {
case JUST_LEFT:
case JUST_RIGHT:
case JUST_CENTER:
this.just = just;
break;
default:
System.out.println("invalid justification arg.");
}
}
public int getMaxChars() {
return maxChars;
}
/** */
/** 设置字符串对齐器的一行最大字符数 */
public void setMaxChars(int maxChars) {
if (maxChars < 0) {
System.out.println("maxChars must be positive.");
} else {
this.maxChars = maxChars;
}
}
/** */
/** 对齐一个字符串 */
public String format(String s) {
StringBuffer where = new StringBuffer();
//从待对其的字符串中取出一段子字符串,子串长度为行最大长度和s长度的较小值
int wantedLength = Math.min(s.length(), this.maxChars);
String wanted = s.substring(0, wantedLength);
//根据对齐模式,将空格插入到合适的位置
switch (this.just) {
case JUST_LEFT:
//左对齐,将空格插入到字符串的右边
where.append(wanted);
pad(where, maxChars - wantedLength);
break;
case JUST_RIGHT:
//右对齐,将空格插入到字符的左边
pad(where, maxChars - wantedLength);
where.append(wanted);
break;
case JUST_CENTER:
//居中对齐,将空格平均插入到字符串的两边
int startPos = where.length();
pad(where, (maxChars - wantedLength) / 2);
where.append(wanted);
pad(where, (maxChars - wantedLength) / 2);
//调整舍入误差
pad(where, maxChars - (where.length() - startPos));
break;
}
//如果原字符串长度大于一行的最大长度,则将余下部分放入下一行
if (s.length() > wantedLength) {
String remainStr = s.substring(wantedLength);
where.append("\r\n" + this.format(remainStr));
}
return where.toString();
}
/** */
/** 在to后面append howMany个空格字符 */
protected final void pad(StringBuffer to, int howMany) {
for (int i = 0; i < howMany; i++) {
to.append(" ");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -