2014-09-13 24 views
1

我在與下面的代碼一個問題:行星超過數字框

public class Stargazing { 
     public static void main(String args[]) { 

     double planets = 840000; 
     double numofsun = 2.5; 
     double total = 0; 

     System.out.println("Galaxy #"+"\t"+"Planets"); 

     for(int i=1;i<12;i++){ 
     double siSky= planets * numofsun; 
     total+=siSky; 
     System.out.println(i+"\t"+total); 
     } 
    } 
    } 

該計劃旨在計算給定的星系中的行星數量,但問題似乎是一次數量的行星數百萬,數十億的開始輸出數字像這樣結束:

5  1.05E7                          
6  1.26E7                          
7  1.47E7                          
8  1.68E7                          
9  1.89E7                          
10  2.1E7                          
11  2.31E7 

我不知道我應該在的地方放置兩倍來實現這一目標。

還要使一個逗號出現,例如:12億

我將最終把更多的列,但它的當務之急,我得到這些列的權利,以使別人不顯示號碼了這麼時髦。

回答

2

使用長數字而不是整數,並使用使用分組的DecimalFormat對象。例如,

import java.text.DecimalFormat; 

public class Foo { 
    private static final String FORMAT_STRING = "0"; 

    public static void main(String[] args) { 
     DecimalFormat myFormat = new DecimalFormat(FORMAT_STRING); 
     myFormat.setGroupingSize(3); 
     myFormat.setGroupingUsed(true); 

     System.out.println(myFormat.format(10000000000000L)); 
    } 
} 

這將輸出:10萬億

編輯,或者如果你必須使用雙打,你總是可以使用System.out.printf(...)它使用的java.util.Formatter的格式化能力。您可以在此處指定數字輸出的寬度,要包含的小數位數以及是否包含組分隔符(使用,標誌)。例如:

public static void main(String args[]) { 
    double planets = 840000; 
    double numofsun = 2.5; 
    double total = 0; 
    System.out.println("Galaxy #" + "\t" + "Planets"); 
    for (int i = 1; i < 12; i++) { 
    double siSky = planets * numofsun; 
    total += siSky; 
    System.out.printf("%02d: %,14.2f%n", i, total); 
    } 
} 

將返回:

使用printf的關鍵是要使用正確的格式說明。

  • %02d表示從int值創建一個數字字符串,2個字符的寬度,如果需要,前導0。
  • %,14.2f表示從浮點數(由f表示)(即14個字符寬),具有2個小數位(如.2所示)和輸出分組(如,標誌所示)創建數字字符串。
  • %n表示打印一個新行,相當於\n用於打印或println語句。

編輯
甚至更​​好,使用類似的格式說明兩個列標題字符串和數據行字符串:

public class Stargazing { 
    public static void main(String args[]) { 
     double planets = 840000; 
     double numofsun = 2.5; 
     double total = 0; 
     System.out.printf("%8s %13s%n", "Galaxy #", "Planets"); 
     for (int i = 1; i < 12; i++) { 
     double siSky = planets * numofsun; 
     total += siSky; 
     System.out.printf("%-8s %,13.2f%n", i + ":", total); 
     } 
    } 
} 

這會打印出:

Galaxy #  Planets 
1:  2,100,000.00 
2:  4,200,000.00 
3:  6,300,000.00 
4:  8,400,000.00 
5:  10,500,000.00 
6:  12,600,000.00 
7:  14,700,000.00 
8:  16,800,000.00 
9:  18,900,000.00 
10:  21,000,000.00 
11:  23,100,000.00 
+0

謝謝氣墊船充滿鰻魚 – hobo 2014-09-13 16:12:56

+0

@hobo:不客氣。請參閱編輯。 – 2014-09-13 16:15:18