Johnathon Corleon
Johnathon Corleon

Reputation: 37

Getting ArrayOutofBoundsException in my for Loop

public class WeightOnPlanetsV1
{
  public static double[] calcWeight(double[] gravity, double[]mass)
  {
    double[] weight = new double[gravity.length];

    for (int i = 0; i < gravity.length; i++) {
        weight[i] = (mass[i] * 1000) / gravity[i];
        weight[i] = weight[i] / 433.59237;
    }

    return weight;
  }

  public static double[] takeFromFile(double[] gravity)throws IOException
  {
    File fileName = new File("GravityResults.txt");
    Scanner inFile = new Scanner(fileName);

    for (int i = 0; i < gravity.length; i++) {
        gravity[i] = inFile.nextDouble();
        gravity[i] = gravity[i] / 10;
    }
    inFile.close();

    return gravity;
  }

  public static void printResults(String[] names, double[] gravity, double weight[])
  {
    System.out.printf("%37s \n","My Weight on the Planets");
    System.out.printf("%5s %20s %15s \n","Planet","Gravity","Weight(lbs)");
    System.out.println("---------------------------------------");
    for (int i = 0; i < names.length; i++) {
        System.out.printf("%5s %10f %15f \n",names[i], gravity[i], weight[i]);
    }
  }

  public static void main(String[] args)throws IOException
  {        
    String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
    double[] weightOnPlanets = {100, 100, 100, 100, 100, 100, 100, 100, 100};
    double[] gravity = {};
    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)};

    double[] gravities = takeFromFile(gravity);
    double[] finalWeights = calcWeight(gravities,masses);

    printResults(names, gravities, finalWeights);
  }  
}

My error comes from

for (int i = 0; i < names.length; i++) {
    System.out.printf("%5s %10f %15f \n",names[i], gravity[i], weight[i]);
}

when I try to print the results. It gives me

java.lang.ArrayIndexOutOfBoundsException: 1
    at WeightOnPlanetsV1.printResults(WeightOnPlanetsV1.java:45)
    at WeightOnPlanetsV1.main(WeightOnPlanetsV1.java:63)

as the error

Upvotes: 1

Views: 138

Answers (5)

Alfro
Alfro

Reputation: 517

Basically, you initialize: double[] gravity = {}; in your main function.

Then you call: double[] gravities = takeFromFile(gravity); Since gravity has no elements, and since in your takeFromFile(double[]) function you have this:

 for (int i = 0; i < gravity.length; i++) {
    gravity[i] = inFile.nextDouble();
    gravity[i] = gravity[i] / 10;
}

which basically reads the file gravity.lenght times (And this is a reaaaally bad idea, btw. You'd have another error if the file had less numbers than the lenght of gravity[])

Anyways, as someone said earlier, this all causes both gravity and gravities to be empty, and so does finalWeights[], since you initialized it using:

double[] finalWeights = calcWeight(gravities,masses);

and since gravities has 0 elements... well, that happens. Now, names[] has 9 elements, which is larger than 0, so that's why in:

System.out.printf("%5s %10f %15f \n",names[i],gravity[i], weight[i]);

you get an ArrayOutOfBounds exception (because you didn't check gravity[] or weight[] sizes, and both turned out to be 0). Which means you need to make sure to initialize gravity[] with a larger lenght than names[]

I personally would rewrite that code. Make an object called "Planet" with the mass, gravity and name attributes and a function calcWeight() or calcWeight(double mass) inside that object which does the same as your function. Then, you can create a Planet[] array in your main function, and also use it intakeFromFile(Planet[] planets) , initializing through file the all planets array and not just the weights. But this is just my preference.

Upvotes: 1

ursa
ursa

Reputation: 4591

Modify your code to work with objects & lists. It becomes much more clear:

class Planet {
    String name;
    double weightOnPlanet;
    double gravity;
    double mass;
    public Planet(...) { ... } // Constructor.
}

public static void main(String[] args) throws IOException {
    List<Planet> planets = new ArrayList<>();
    planets.add(new Planet(...));
    ...
}

Upvotes: 0

Milad Qasemi
Milad Qasemi

Reputation: 3059

double[] gravity = {}; is an empty array so you have to fill it like other arrays

Upvotes: 0

Eran
Eran

Reputation: 393846

Your problem starts in takeFromFile which receives an empty array (double[] gravity = {};) and returns an empty array.

Later, all the loops that iterate over the gravity (or gravities) array do nothing, while the loop that iterates from 0 to names.length - 1 (in printResults) causes the ArrayIndexOutOfBoundsException, since it assumes that names and gravity arrays have the same length.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240908

You check the bound of names array and you access gravity and weight assuming they have same or greater length as names

Upvotes: 3

Related Questions