Reputation: 127
I'm trying to code a for loop to display a two-dimensional array of doubles rounded to one decimal place. However, whenever I run my code it displays only the last column of data correctly, and displays the preceding columns with two extra decimal points. Here is my code:
public void calcDistance(double [] radians, int [] initialVelocity, double [][] answers)
{
for(int rowIndex = 0; rowIndex < initialVelocity.length; rowIndex++)
{
for(int colIndex = 0; colIndex < radians.length; colIndex++)
{
answers[rowIndex][colIndex] = ((Math.pow(initialVelocity[rowIndex], 2) * Math.sin(radians[colIndex]))/ 9.8);
System.out.print(initialVelocity[rowIndex] + " ");
System.out.printf("%9.1f", answers[rowIndex][colIndex]);
}
System.out.println();
}
}
And it displays something like this:
20 17.220 20.420 23.420 26.220 28.920 31.3
25 27.025 31.925 36.625 41.025 45.125 48.9
30 38.830 45.930 52.730 59.030 64.930 70.4
35 52.835 62.535 71.735 80.335 88.435 95.8
40 69.040 81.640 93.640 104.940 115.440 125.1
45 87.345 103.345 118.545 132.845 146.145 158.3
50 107.850 127.650 146.350 164.050 180.450 195.4
Why do some numbers have 3 digits after the decimal point?
Upvotes: 1
Views: 49
Reputation: 57114
You should change your for-loop to be:
for(int rowIndex = 0; rowIndex < initialVelocity.length; rowIndex++)
{
System.out.print(initialVelocity[rowIndex] + " ");
for(int colIndex = 0; colIndex < radians.length; colIndex++)
{
answers[rowIndex][colIndex] = ((Math.pow(initialVelocity[rowIndex], 2) * Math.sin(radians[colIndex]))/ 9.8);
System.out.printf("%9.1f ", answers[rowIndex][colIndex]);
}
System.out.println();
}
What previously happened is that you output the following in that exact order:
20[space]
17.2
20[space]
20.4
20[space]
etc.
Those appended to one another yield
20 17.220 20.420 etc.
You should print the initialVelocity
only once per line - at the beginning before the inner loop runs. the inner loop-values have to separated with a space.
Upvotes: 2