2015-12-02 164 views
1
System.out.println("Year  StartBalance  Interest Earned  End Balance"); 
    for (int i = 1; i<Years+1; i++) { //table: year number, principal at beginning, total interest earned, principal at the end 
     double AmountPerQuarter = (Principal * (1 + Rate/400)); 
     NewPrincipal = AmountPerQuarter; 
     double InterestEarned = NewPrincipal - Principal; 
     System.out.printf(i+ "%13s %15s %22s",Principal,InterestEarned,NewPrincipal); 
     Principal = NewPrincipal; 
    } 

嗨,我是計算機科學專業的學生,​​在這個例子中,我對格式化有點困惑。帶for循環和格式的表格

這個應該做的是在頂部創建Year,StartBalance等的表格,然後將該線段打印爲一行,然後當循環重複時,它會開始一個新行,但是使用printf,循環所做的一切只是打印在一行上,這抵消了我想要對錶進行的操作。

例如,它結束了,如:

Year StartBalance  InterestEarned  Endbalance 

1..........500................20............520252040580 

,而不是開始第二年新線。另外,作爲一個側面問題,當我使用像「%13s」這樣的格式來創建13個空格時,我將如何製作它,以便它打印的內容四捨五入到小數點後兩位?我知道「%.2f」是什麼使用,但我不知道如何將它們兩個都結合起來,因此我可以創建13個空格並具有舍入小數位數的數字。

對不起,如果這看起來不清楚,我試過搜索,但無法找到答案。

謝謝!

+0

使用'\ N'新線。 – brso05

回答

1

要創建一個新的行,你需要一個換行符,這可以通過添加「\ n」,還是使用空白的System.out.println(「」)創建;(它創建一個新的行字符)。下面是前者:

變化

System.out.printf(i+ "%13s %15s %22s",Principal,InterestEarned,NewPrincipal); 

System.out.printf(i+ "%13s %15s %22s\n",Principal,InterestEarned,NewPrincipal); 
0

你需要%n對換行,也是一個整數%d。喜歡的東西

System.out.printf("%12d %13s %15s %22s%n", i, Principal, InterestEarned, 
     NewPrincipal);