Write a program in Java, you have to input from keyboard two matrix with real dimensions NxM and MxP, multiply those matrix and write the result in a file, all matrix must contain double objects.
My code:
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Scanner;
public class MatriceMain {
private static Scanner scanner;
public static void main(String[] args) {
try{
BufferedReader in_stream_char =
new BufferedReader(new InputStreamReader(System.in));
PrintStream out_stream = new PrintStream(
new FileOutputStream("out.txt"));
int N,M,P,i,j,sum=0,k;
System.out.println("Dati numarul de linii(N) si nr de coloane(M) ale primei matrici: ");
N = Integer.parseInt(in_stream_char.readLine());
M = Integer.parseInt(in_stream_char.readLine());
double first[][] = new double[N][M];
System.out.println("Dati elementele primei matrici: ");
for ( i = 0 ; i < N ; i++ )
for ( j = 0 ; j < M ; j++ )
first[N][M] = Integer.parseInt(in_stream_char.readLine());
System.out.println("Dati numarul de linii(N) si nr de coloane(M) ale primei matrici: ");
M = Integer.parseInt(in_stream_char.readLine());
P = Integer.parseInt(in_stream_char.readLine());
double second[][] = new double[M][P];
System.out.println("Dati elementele matricei secunde: ");
for ( i = 0 ; i < M ; i++ )
for ( j = 0 ; j < P ; j++ )
second[M][P] = Integer.parseInt(in_stream_char.readLine());
double multiply[][] = new double[N][P];
for(i=0;i<N;i++)
{
for(j=0;j<P;j++)
{
for(k=0;k<M;k++)
{
sum= (int) (sum + first[i][k]*second[k][j]);
}
multiply[i][j] = sum;
sum=0;
}
}
System.out.println("");
out_stream.println();
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
System.out.print(multiply[i][j]+"\t");
}
out_stream.close();
} catch(IOException e) {
System.out.println("Eroare la operatiile de intrare- iesire!");
System.exit(1);
}
}
}
ERRORS: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at MatriceMain.main(MatriceMain.java:30)
How can you do it? Do I need to put the first and the second in two separate files? Is the code correct, properly?