格式化Java控制台表

时间:2013-10-01 21:53:08

标签: java netbeans console

我正在开发一个项目,该项目输出一个价值表(月,利息,付款,总金额等)。我在NetBeans中将值打印到控制台的列均匀分布,并且正常运行,但我上面还有一条打印行,以便显示标题,这与其他列不匹配。如果没有任何意义,我附上了我正在使用的代码。

    System.out.println("Month \t\t Start Balance \t Interest \t\t Principal \t Payment \t End Balance");

    while (true) {
        i++;
        compCost = round(compCost);
        System.out.print(i + "\t \t");//month
        System.out.print(patternFormatter.format(compCost) + "  \t ");//original balance
        double interest = (rate / 12) * compCost;
        interest = round(interest);
        System.out.print(patternFormatter.format(interest) + "  \t \t");//interest
        sum = sum + interest;

        compCost = compCost + interest;//add interest
        payment = round(payment);

        if (compCost > payment) {//check if payment is bigger than the cost left
            compCost = compCost - payment;
            double principal = payment - interest;
            principal = round(principal);
            System.out.print(patternFormatter.format(principal) + "\t \t");//principal
            System.out.print(patternFormatter.format(payment) + "\t \t");//payment
        } else {
            System.out.print(patternFormatter.format(compCost - interest) + "\t \t");//principal
            System.out.print(patternFormatter.format(compCost) + "\t \t");//payment
            compCost = 0;
        }
        compCost = round(compCost);
        System.out.print(patternFormatter.format(compCost));

        System.out.println("");

2 个答案:

答案 0 :(得分:1)

使用j-text-utils您可以打印以控制表格,如: enter image description here

它很简单:

TextTable tt = new TextTable(columnNames, data);                                                         
tt.printTable();   

API还允许排序和行编号......

答案 1 :(得分:0)

如果您要打印的列不比控制台的标签宽度宽,则标签只会对齐您的文本。举个例子:

public class SO {
  public static void main(String[] args) {
    int[][] data = new int[][] {
      {1,2,        3, 4},
      {2,4,314159265, 8},
      {4,8,       12,16}};
    for(int[] row : data) {
      for(int col : row) {
        System.out.print(col+"\t");
      }
      System.out.println();
    }
  }
}

这会产生以下输出:

1   2   3   4   
2   4   314159265   8   
4   8   12  16  

如果您尝试在文本控制台中对齐这些值,则需要计算最宽的元素并自行生成填充。有些库可以让这更容易。