2014-01-14 61 views
1

嗨,我挖了一段時間,但無法找到與此主題相關的問題。我正在編寫一個程序,輸出一張表格,列出信用卡用戶的最低付款和餘額。問題發生在代碼的最後一部分,我必須在輸出之間放置空格,並將輸出格式化爲2位小數。格式化小數位格式化System.out.print Java

在此先感謝!

我的代碼:

public static void main(String[] args) { 

     double minPay = 0; 

     Scanner key = new Scanner(System.in); 
     System.out.printf("Please Enter your credit card balance: "); 
     double balance = key.nextDouble(); 
     System.out.printf("Please Enter your monthly interest rate: "); 
     double rate = key.nextDouble(); 

     System.out.printf("%-6s%-10s%-10s\n", "", "Min.Pmt", "New Balance"); 
     System.out.printf("------------------------------\n"); 
     for (int i=0; i<12; i++){ 
     minPay = balance*0.03; 

     if (minPay<10){ 
      minPay=10.00; 
     } 

     double add = (balance*(rate/100)); 
     balance += add; 
     balance -= minPay; 
     System.out.printf("%-6s%-10.2f%-10.2f\n", i+1 + ".", "$" + minPay, "$" + balance); 
+1

我認爲'DecimalFormat'完全適合這裏:) –

+0

...什麼是預期的輸出(舉一個例子),你會得到什麼呢? – chrylis

回答

0

使用DecimalFormat格式化任意數量的

DecimalFormat df = new DecimalFormat("0.00"); 
String result = df.format(44.4549); 
1

在最後一行中,你對有關參數的printf創造,而不是漂浮在格式字符串兩個字符串,預計。在Java中,當你爲某個字符串「添加」一個字符串時,另一個參數被轉換爲一個字符串,結果是另一個字符串。

將美元符號移動到printf格式字符串中,並將參數作爲浮點數傳遞。

+0

這樣做!非常感謝! :d – kabloo12