さて、このプログラムの目的は、ファイルで満たされた2つの行列を加算することです。私のプログラムは最初の配列を作成して印刷しますが、2番目の配列を塗りつぶして印刷しようとすると、最初の配列を塗りつぶして再印刷します。私は理由を正当化することができますが、それを修正する方法についてはわかりません。あなたは以下のコードで表示されますようファイルから行列配列を作成しようとしましたが、プログラムは同じ行列を2つ返しますか?
はここだけの行と列を決定するためにされているファイル
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
3および4です。だから、最初の配列/行列は次のようになります。ここでは
2 1 7 -10
0 5 -3 12
1 7 -2 -5
そして第二に
0 1 2 3
4 5 6 7
8 9 0 1
は私のコードです:
public class Matrices {
public static int[][] readMatrix(int rows, int columns, String file) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(file));
rows = fileReader.nextInt();
columns = fileReader.nextInt();
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
そして、私のドライバー:
public class MatricesDriver {
public static void main(String[] args)throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
File file = new File(filename);
int rows = 0;
int columns = 0;
int[][] a = Matrices.readMatrix(rows, columns, filename);
int[][] b = Matrices.readMatrix(rows, columns, filename);
Matrices.printMatrix(a);
System.out.println();
Matrices.printMatrix(b);
}
}
コード最初のマトリックスの塗りつぶしと印刷には問題ありませんが、第2のマトリックスでも同じことをすることはできません。出力は次のとおりです。
Enter name of file:
data/MAtrices.txt
2 1 7 -10
0 5 -3 12
1 7 -2 -5
2 1 7 -10
0 5 -3 12
1 7 -2 -5
もう一度最初の行列が出力されます。同じファイルを使用して2つの別々の行列を作成するにはどうすればよいですか?
うん、それはうまくいくようだ。しかし私はまた別の質問があります。 2つの異なるサイズの2D配列をこの方法で作成することは可能でしょうか?たとえば、上の例では2つの3x4行列を追加していました。同じファイルから、2つの2x2配列の直後の違いを取得したいのですが?それは可能ですか? – bgb102
これは、2つの2x2行列の前に行があり、次の行列の行と列を指定する(つまり、2 2)ためです。次の行をスキャンし、次の行列の数列が正しく処理されるように更新するヘルパーメソッドを実装できます。 –