日期:2014-05-19  浏览次数:20623 次

String数组问题
现有一个数组
String[] str = new String[]{"A","B","C","D","E","F"};

输出为: -------------------------------
  | A | B | C |
  -------------------------------
  | D | E | F |
  -------------------------------


这个线都是连在一起的,是一个两行三列表格,我这里不想往上传图片了,就随便画了一下



------解决方案--------------------
Java code

String[] str = new String[]{"A","B","C","D","E","F"};
        for (int i = 0; i < str.length; i++) {
            if(i>0&&i%3==0) {
                System.out.println();
            }
            System.out.print(str[i] + " ");
        }

------解决方案--------------------
就是循环,三个元素换一次行
Java code
String[] str = new String[]{"A","B","C","D","E","F"};
String line = "-------------"; //计算好元素占的横向空间
System.out.println(line);
System.out.print("|");
for (int i = 0; i < str.length; i++) {
    System.out.printf(" %s |", str[i]);
    if ((i+1)%3 == 0) { //3个元素换一次行,并打印第一个竖线
        System.out.printf("\n%s\n%s", line, i==str.length-1 ? "" : "|");
    }
}