比如输两行字,可是上一行的字只有一位数,第二行的字有二位数,怎么对齐输出来啊
就是每一列对齐啊,如果第一行有一位数的数,又有二位数的数,用什么语句可以使他每列对齐啊
只能用空格或制表位"\t"来对齐了
首先根据需要把每一列的宽度设死,比如每列10个字符,在输出的时候,每输出一列,后面加上这列的宽度减去已经输出列数的字符数。
如下:
public class Col {
/**
* @param args
*/
public static void main(String[] args) {
String[][] str={{"12","5","998","154682"},{"5","998","12","182"}};
int col=10;
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
System.out.print(str[i][j]+getPlace(col-str[i][j].length()));
}
System.out.println();
}
}
public static String getPlace(int count){
String str="";
for (int i = 0; i < count; i++) {
str+=" ";
}
return str;
}
}
首先根据需要把每一列的宽度设死,比如每列10个字符,在输出的时候,每输出一列,后面加上这列的宽度减去已经输出列数的字符数。
如下:
public class Col {
/**
* @param args
*/
public static void main(String[] args) {
String[][] str={{"12","5","998","154682"},{"5","998","12","182"}};
int col=10;
for (int i = 0; i < str.length; i++) {
for (int j = 0; j < str[i].length; j++) {
System.out.print(str[i][j]+getPlace(col-str[i][j].length()));
}
System.out.println();
}
}
public static String getPlace(int count){
String str="";
for (int i = 0; i < count; i++) {
str+=" ";
}
return str;
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 推荐于2017-09-09
java输出可以定义每行开头的空格数,示例如下:
public class ceshi{public static void main(String[] args){
for(int i=0;i<=10;i++){
System.out.printf("%10s", i);
}
//%10s 是表示对应的空格10格
//i 是将要输出的
}
}
第2个回答 2009-06-27
System.out.println("\t" + "5");
System.out.println("\t" + "55");
System.out.println("\t" + "55");
第3个回答 2009-06-27
左对齐?
右对齐?
右对齐?