2012-03-24 45 views
4

這是我的代碼(好吧,其中一些)。我的問題是,我可以得到前9位數字,以前100表示​​,數字10 - 99表示前導0.Java System.out.print格式

我必須顯示所有的360每月付款,但如果我不所有月份的數字都是相同的長度,那麼我最終會得到一個輸出文件,它會繼續向右移動並抵消輸出的外觀。

System.out.print((x + 1) + " "); // the payment number 
System.out.print(formatter.format(monthlyInterest) + " "); // round our interest rate 
System.out.print(formatter.format(principleAmt) + "  "); 
System.out.print(formatter.format(remainderAmt) + "  "); 
System.out.println(); 

結果:

8    $951.23    $215.92   $198,301.22       
9    $950.19    $216.95   $198,084.26       
10    $949.15    $217.99   $197,866.27       
11    $948.11    $219.04   $197,647.23 

我想看到的是:

008    $951.23    $215.92   $198,301.22       
009    $950.19    $216.95   $198,084.26       
010    $949.15    $217.99   $197,866.27       
011    $948.11    $219.04   $197,647.23 

什麼其他的代碼,你需要從我的課,可以幫忙看看?

回答

9

由於您使用的格式化爲它的其餘部分,只要使用的DecimalFormat:

import java.text.DecimalFormat; 

DecimalFormat xFormat = new DecimalFormat("000") 
System.out.print(xFormat.format(x + 1) + " "); 

另類,你可以使用printf在整行中完成整個工作:

System.out.printf("%03d %s %s %s \n", x + 1, // the payment number 
formatter.format(monthlyInterest), // round our interest rate 
formatter.format(principleAmt), 
formatter.format(remainderAmt)); 
+0

我所做的是: import java.text.DecimalFormat; 然後,我用Adam的建議進行了一點編輯。謝謝你,亞當! DecimalFormat newFormat = new DecimalFormat(「000」); System.out.print(newFormat.format(x + 1)+「」); > 008 $ 951.23 $ 215.92 $ 198,301.22 009 $ 950.19 $ 216.95 $ 198,084.26 010 $ 949.15 $ 217.99 $ 197,866.27 011 $ 948.11 $ 219.04 $ 197,647.23 – RazorSharp 2012-03-24 07:26:13

5

由於您使用的是Java,printf可從1.5版

你可以使用它像這樣

System.out.printf("%03d ", x);

例如:

System.out.printf("%03d ", 5); 
System.out.printf("%03d ", 55); 
System.out.printf("%03d ", 555); 

會給你

005 055 555

作爲輸出

見:System.out.printfFormat String Syntax

3

東西喜歡這個

public void testPrintOut() { 
    int val1 = 8; 
    String val2 = "$951.23"; 
    String val3 = "$215.92"; 
    String val4 = "$198,301.22"; 
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4)); 

    val1 = 9; 
    val2 = "$950.19"; 
    val3 = "$216.95"; 
    val4 = "$198,084.26"; 
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4)); 
} 
0

你確定你想要的 「055」,而不是 「55」?某些程序將前導零解釋爲八進制,因此它將055(十進制)45而不是(十進制)55讀爲012.

例如,改變System.out.printf("%03d ", x);更簡單的System.out.printf("%3d ", x);

0

只需使用\t空間吧。

例子:

System.out.println(monthlyInterest + "\t") 

//as far as the two 0 in front of it just use a if else statement. ex: 
x = x+1; 
if (x < 10){ 
    System.out.println("00" +x); 
} 
else if(x < 100){ 
    System.out.println("0" +x); 
} 
else{ 
    System.out.println(x); 
} 

還有其他的方法來做到這一點,但是這是最簡單的。