代码打印意外结果

时间:2017-01-31 02:43:05

标签: java math printing gravity

出于某种原因,水星和金星在重量场打印无限。有谁能看到这个问题?这段代码对你们有用吗?所有其他行星似乎工作正常。提前谢谢!

import java.util.Scanner;

public class Weight
{

    static double getGravity(String name) throws IOException
    {

        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)};
        int i = java.util.Arrays.asList(names).indexOf(name);

        return 6.67 * Math.pow(10, -11) * masses[i] / Math.pow(radii[i]*1000, 2);

    }

    static double convertWeight(double originalWeight, double currentGravity, double newGravity)
    {
        return originalWeight * (newGravity / currentGravity);
    }

    static void printResults(String name, double gravity, double weight)
    {
        System.out.printf("%-10s %-8.1f %-8.1f\r\n", name, gravity, weight);
    }

    public static void main(String[] args) throws IOException
    {

        Scanner in;
        System.out.print("Enter your weight in lbs: ");
        in = new Scanner(System.in);
        double earthWeight = in.nextDouble();

        String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
        //PLUTO IS NOT A PLANET!

        double[] gravity = new double[names.length];
        double[] weight = new double[names.length];
        System.out.printf("%-10s %-8s %-8s\r\n============================================\r\n", "Planet", "Gravity", "Weight (lbs) ");
        for(int i=0; i<gravity.length; i++)
        {
            gravity[i] = getGravity(names[i]);
            weight[i] = convertWeight(earthWeight, gravity[2], gravity[i]);
            printResults(names[i], gravity[i], weight[i]);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

引力[2]必须在循环之前设置,或者除以0直到地球。