我是一個完整的Java新手,我試圖乘以兩個二維數組,如你將乘以兩個矩陣。下面的程序只適用於方矩陣,但不適用於其他程序。我似乎無法弄清楚我出錯的地方。如果有人能幫助我,那會很好。試圖乘二維數組(如在矩陣乘法),但只適用於矩陣矩陣
import java.util.Scanner;
public class TwoDMatrix {
public static void main (String [] args){
Scanner scanme = new Scanner(System.in);
//Input dimensions of Matrix A
System.out.println("Enter the dimensions (row x column) of Matrix A");
int rowA = scanme.nextInt();
int columnA = scanme.nextInt();
int [][] matA = new int [rowA][columnA];
//Input dimensions of Matrix B
System.out.println("Enter the dimensions (row x column) of Matrix B");
int rowB = scanme.nextInt();
int columnB = scanme.nextInt();
int [][] matB = new int [rowB][columnB];
// Declaring new variables
int [][] product = new int [columnA][rowB];
int rowCountA, columnCountA, rowCountB, columnCountB;
int rowCountProduct, columnCountProduct;
int sum;
String divider = "---------";
// Input values of Matrix A
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%s%d%s%d%s", "Enter the value at A(", rowCountA, ",", columnCountA, ")");
matA[rowCountA][columnCountA] = scanme.nextInt();
}
}
// Input values of Matrix B
for (rowCountB = 0; rowCountB < rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%s%d%s%d%s", "Enter the value at B(", rowCountB, ",", columnCountB, ")");
matB[rowCountB][columnCountB] = scanme.nextInt();
}
}
//Calculate product of the two matrices
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
sum = 0;
for (columnCountA=0, rowCountB=0; columnCountA<columnA && rowCountB<rowB; columnCountA++, rowCountB++){
sum += (matA[rowCountProduct][columnCountA] * matB[rowCountB][columnCountProduct]);
}
product[rowCountProduct][columnCountProduct] = sum;
}
}
//Prints the input matrix A
System.out.printf("%n%s%n%s%n", "Matrix A:", divider);
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%5d", matA[rowCountA][columnCountA]);
}
System.out.println();
}
//Prints the input matrix B
System.out.printf("%n%s%n%s%n", "Matrix B:", divider);
for (rowCountB = 0; rowCountB< rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%5d", matB[rowCountB][columnCountB]);
}
System.out.println();
}
//Prints the product
System.out.printf("%n%s%n%s%n", "Product", divider);
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
System.out.printf("%5d", product[rowCountProduct][columnCountProduct]);
}
System.out.println();
}
}
}
你這是什麼意思是「它不工作」?拋出任何異常或錯誤的結果? –
如果兩個矩陣都是正方形且具有相同的尺寸,那麼程序工作得很好。例如: 矩陣A是2×2,矩陣B是2×2,或者 矩陣A是3×3,矩陣B是3×3。 在這些條件下它工作正常。 但是如果 矩陣A是2x3並且矩陣B是3x2或 矩陣A是1x2並且矩陣B是2x3, 在這些條件下,它給出了arrayIndexOutOfBound錯誤。 –
您是否嘗試應用我給您的僞代碼? – Dici