2013-10-01 55 views
0

我正在處理一個輸出值(月,利息,支付,金額總額等)表的項目。我將列的值打印到NetBeans中的控制檯,均勻間隔地運行正常,但爲了顯示標題,我還有一個單獨的打印行,這與其餘列不匹配。如果沒有任何意義,我附上了我正在使用的代碼。格式化Java控制檯表中斷

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(""); 
+0

你能請將代碼解析爲相關的輸出代碼? – nhgrif

+0

代碼太多。將其細化到具體細節。 – user2339071

+0

好吧我修剪下來 – Super12464

回答

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 

如果你想在一個文本控制檯調整這些值,則需要計算出最寬的元素,並生成填充自己。有些庫使得這更容易。

+0

我對這個庫沒有任何經驗http://sourceforge.net/projects/texttablefmt/(我通常只是轉儲到TSV格式,讓電子表格應用程序對齊),但它出現了作爲谷歌搜索「Java文本表生成器」的高成果, –

1

使用j-text-utils您可以打印到控制檯就像一個表: enter image description here

它簡單:

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

的API還允許分揀和行編號...