2014-01-14 59 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