好友
阅读权限10
听众
最后登录1970-1-1
|
居中 必须要有参考物,如果没有参考物,居不居中就没意义了。
假如Knowle is Power要分三行居中,那必须有个参考物,
假如参考物是20个"-"组成的虚线:--------------------
那它们居中就是这样子的,请问LZ是不是想要这种效果呢?
这是代码:
public class Demo {
public static void main(String[] args) {
//打印虚线
printMsg("", 20, '-', "");
printMsg("Knowledge", 20, ' ', "CENTER");
printMsg("is", 20, ' ', "CENTER");
printMsg("Power", 20, ' ', "CENTER");
//打印虚线
printMsg("", 20, '-', "");
printMsg("Knowledge", 20, ' ', "LEFT");
printMsg("is", 20, ' ', "LEFT");
printMsg("Power", 20, ' ', "LEFT");
printMsg("", 20, '-', "");
printMsg("Knowledge", 20, ' ', "RIGHT");
printMsg("is", 20, ' ', "RIGHT");
printMsg("Power", 20, ' ', "RIGHT");
printMsg("", 20, '-', "");
}
public static void printMsg(String msg, int num, char placeholder, String align){
if(msg != null && msg.length() > 0){
if(msg.length() > num){
System.out.println(msg);
}else{
int spaceNum = num - msg.length();
if(align.equals("CENTER")){
for(int i = 0; i < spaceNum; i++){
if(i < spaceNum/2){
System.out.print(placeholder);
}else if(i == spaceNum/2){
System.out.print(msg);
}else{
System.out.print(placeholder);
}
}
}else if(align.equals("LEFT")){
System.out.print(msg);
for(int i = 0; i < spaceNum; i++){
System.out.print(placeholder);
}
}else if(align.equals("RIGHT")){
for(int i = 0; i < spaceNum; i++){
System.out.print(placeholder);
}
System.out.print(msg);
}
System.out.println();
}
}else{
for(int i = 0; i< num; i++){
System.out.print(placeholder);
}
System.out.println();
}
}
} |
|