格子中输出
"%" + (width-2-s.length())/2 + "s%s%" + (width-2-s.length() - (width-2-s.length())/2) + "s"
String.format(); 为格式化字符串,用%s填充
"%" + (width-2-s.length())/2 + "s" 为字符串前的空格
"%s" 对应下一行的字符串
"%" + (width-2-s.length() - (width-2-s.length())/2) + "s" 对应字符串后面的空格
package java_2015_C;
public class Main005_格子中输出 {
public static void main(String[] args) {
stringInGrid(10,6,"abcd1234");
}
public static void stringInGrid(int width, int height, String s) {
if(s.length()>width-2) s = s.substring(0,width-2);
System.out.print("+");
for(int i=0;i<width-2;i++) System.out.print("-");
System.out.println("+");
for(int k=1; k<(height-1)/2;k++){
System.out.print("|");
for(int i=0;i<width-2;i++) System.out.print(" ");
System.out.println("|");
}
System.out.print("|");
String ff = "%" + (width-2-s.length())/2 + "s%s%" +
(width-2-s.length() - (width-2-s.length())/2) + "s";
System.out.print(String.format(ff,"",s,""));
System.out.println("|");
for(int k=(height-1)/2+1; k<height-1; k++){
System.out.print("|");
for(int i=0;i<width-2;i++) System.out.print(" ");
System.out.println("|");
}
System.out.print("+");
for(int i=0;i<width-2;i++) System.out.print("-");
System.out.println("+");
}
}
注释掉需要填写的代码部分,可得如下结果:
so,需要填空部分为 字符串的格式