Reputation: 1
I am trying to create an array that uses other arrays in an algebraic expression, but I don't end up with an array of the same length as the ones put in. Here's the code:
public static double[] calcGravity(double[] radius, double[] mass)
{
double[] calcGravity = {};
radius = new double[] {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195};
mass = new double[] {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22};
for(int i = 0; i<radius.length; i ++)
{
calcGravity = new double[] {(((6.67E-11)*(mass [i]))/Math.pow(radius[i] * 1000, 2))};
System.out.println(calcGravity);
}
System.out.println("calcGravity.length = " + calcGravity.length);
return calcGravity;
}
What ends up happening is the calcGravity array only has an index of 0. So, after each loop of the for statement it writes over the last value calculated for calcGravity. My main question is how do I create an array that keeps each value of calcGravity after each for loop?
Upvotes: 0
Views: 48
Reputation: 860
public static double[] calcGravity(double[] radius, double[] mass)
{
double[] calcGravity;
radius = new double[] {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195};
mass = new double[] {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22};
calcGravity = new double[radius.length]; // Making the array size length
// equal to the radius length.
for(int i = 0; i < radius.length; i++)
{
calcGravity[i] = (((6.67E-11)*(mass [i]))/Math.pow(radius[i] * 1000, 2));
System.out.println(calcGravity);
}
System.out.println("calcGravity.length = " + calcGravity.length);
return calcGravity;
}
Note that you would have to make sure that radius.length == mass.length == calcGravity.length
or else the loop wouldn't work.
Upvotes: 1