user2874393
user2874393

Reputation: 1

Static Methods and Arrays

I have to write a program to determine the surface gravity on each planet in our solar system, and have it print out a chart along with writing it to a text file.

I have to use different Static Methods in my program and I have to have the gravity, mass, and radius of each planet written to an array.

What my problem is, is that I'm pretty sure I have the code correct but I keep getting an ArrayOutOfBoundsException at calcGravity, but I don't think my array is out of bounds. I'm doing 9 planets and my array is set to 9.

I tried double[] gravity = {9}; and also double[] gravity = {} but it still won't work correctly. I'm not really sure what to do at this point

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class Gravity
{

public static double[] calcGravity(double[] radius, double[] mass)
{
    double[] gravity = {9};
      for(int i = 0; i < 9; i++)
    {
      gravity[i] = (6.67E17 * mass[i]) / (radius[i] * radius[i]);            
    }
    return gravity;
}

public static void printResults(String[] name, double[] radius, double[] mass, double       gravity[])
{
        System.out.printf("%9s %8s %6s %7s","Planet", "Diameter (km)", "Mass (kg)", "g  (m/s^2)\n"); 
        System.out.println("----------------------------------------------------");
        for(int i = 0; i < 9; i++)
        {
           System.out.printf("%9s %8s %6s %7s", name[i], Math.pow(radius[i], 2), mass[i], gravity[i]); 
        }

}

//print the gravity values to text file
public static void printToFile(double[] gravity)throws IOException
{
    PrintWriter outFile = new PrintWriter (new File("gravity data.txt"));
    for(int a = 0; a < 9; a++)
    {
     outFile.println(gravity[a]);
    }
}

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[] mass = {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22}; 

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

    // Output
    printResults(names, radii, mass, gravities);
    printToFile(gravities);


} //end main
}//end class

Upvotes: 0

Views: 872

Answers (1)

libik
libik

Reputation: 23049

This line creates array of size 1, with number 9 inside :

double[] gravity = {9};

You want

double[] gravity = new double[9];

which creates array of double with 9 empty "boxes" inside.

PS : Pluto is not planet anymore :)

Upvotes: 4

Related Questions