java用printf显示和格式化

时间:2013-12-11 23:32:39

标签: java arrays format printf

我对如何使用printf进行展示有疑问。我用了四次printf。前两次和最后一次,它运作良好。第三个没有。我希望它具有与其他值相同的格式。我怎样才能解决这个问题?任何帮助将不胜感激。我使用格式%15.2f来显示它,当我编译并执行它时,它只是给了我这个:

run:
    Mercury          Venus          Earth           Mars        Jupiter         Saturn         Uranus        Neptune          Pluto
    2439.70        6051.90        6378.00        3402.50       71492.00       60270.00           25562.00       24774.00        1195.00
330220000000000000000000.004868500000000000000000000.005973600000000001000000000.00641850000000000000000000.001898600000000000200000000000.00568459999999999960000000000.0086810000000000000000000000.00102430000000000000000000000.0013120000000000000000000.00
       3.70           8.87           9.79           3.70          24.78          10.44           8.86          11.13           0.61
BUILD SUCCESSFUL (total time: 0 seconds)

下面是我的代码片段(我第三次使用printf的地方有额外的'/':

public static void printResults(String[] name, double[] radius, double[] mass, double[] gravity)
{
        // fill in code here
        for(int i = 0; i < name.length; i++){
            System.out.printf("%15s", name[i]);
        }
        System.out.println();

        for(int i = 0; i < radius.length; i++){
            System.out.printf("%15.2f", radius[i]);
        }
        System.out.println();
        //////////////////
        for(int i = 0; i < mass.length; i++){
            System.out.printf("%15.2f", mass[i]);
        }
        System.out.println();

        for(int i = 0; i < gravity.length; i++){
            System.out.printf("%15.2f", gravity[i]);
        }
        System.out.println();
}

//print the gravity values to text file
public static void printToFile(double[] gravity)throws IOException
{
    // fill in code here
}

public static void main(String[] args)throws IOException
{
    // Initialize variables
    String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
    double[] radii = {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195};
    double[] masses = {3.3022 * Math.pow(10,23), 4.8685 * Math.pow(10,24), 5.9736 * Math.pow(10,24), 6.4185 * Math.pow(10,23),
                1.8986 * Math.pow(10,27), 5.6846 * Math.pow(10,26), 8.6810 * Math.pow(10,25), 1.0243 * Math.pow(10,26), 1.312 *
                    Math.pow(10,22)};
    // or using big E notation:
    // double [] mass = {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22}; // See IMACS double lesson for big E notation

    // Processing
    double[] gravities = calcGravity(radii, masses);

1 个答案:

答案 0 :(得分:1)

输出看起来很奇怪,因为质量值非常长,特别是在以十进制数字打印时。 printf不会截断超出给定字段宽度的值。

您可能希望在打印质量时使用e。它将以科学记数法打印出值,这可能更适合大值。

for(int i = 0; i < mass.length; i++){
    System.out.printf("%15.2e", mass[i]);
}
相关问题