すべてを正確に計算することから始めたいと思います。私が抱いている唯一の問題は、入力した2D配列を印刷しようとしていて、各列の合計をどのようにフォーマットするかです。数値を追加する際の書式設定の問題列ごと[Java]
これは3in1プログラムの一部です。 2番目の部分については、3x4の2D配列に12個の数字を入力する必要があります。コンソールは、入力した配列を返し、合計を列で返します。
これは、それがどのように見えるべきかです:
Enter 3 rows and 4 columns:
1 2 3 4
5 6 7 8
9 10 11.2 12.5
You entered:
1.0 2.0 3.0 4.0
5.0 6.0 7.0 8.0
9.0 10.0 11.2 12.5
The sums are:
15.0 18.0 21.2 24.5
は、これはこれまでのところ私のコードです:
else if(choice == 2) {
// declare the 3x4 array
System.out.print("Enter a 3 by 4 matrix row by row: ");
double[][] myArray = new double[3][4];
// set up the array as an input
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; j++)
myArray[i][j] = input.nextDouble();
feature2(myArray);
} // end of choice 2 block
private static void feature2(double[][] myArray){
System.out.println("You entered: ");
// return the entered array in double form
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
// calculate the sums column by column and display the results
for(int column = 0; column < myArray[0].length; column++) {
double total = 0;
for(int row = 0; row < myArray.length; row++)
total += myArray[row][column];
System.out.println("The sums are: " + total);
}
} // end of feature 2
コードが立つように、これはコンソール上に読み込むものです:
Enter a 3 by 4 matrix row by row:
1 2 3 4
5 6 7 8
9 10 11.2 12.5
You entered:
[[email protected] [[email protected] [[email protected] The sums are: 15.0
The sums are: 18.0
The sums are: 21.2
The sums are: 24.5
ご覧のとおり、正しく計算されますが、正しくフォーマットされません。書式設定の手助けができたら、ここから取り出せます。
ありがとうございます。残っている唯一の事は、私の投稿の「コード」の最初のブロックの最後に表示されているように、合計を1行に印刷する必要があることです。 –
私の答えを今チェックして、私はあなたのコメントに関するいくつかのものを追加しました。 –
ありがとうございます。それはうまくいった! –