0

我正在开发一个输出值表(月、利息、付款、总金额等)的项目。我在 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("");
4

2 回答 2

1

使用j-text-utils您可以打印到控制台,例如: 在此处输入图像描述

它很简单:

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

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

于 2013-12-25T10:45:19.097 回答
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  

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

于 2013-10-01T22:14:00.970 回答