Write a program in java that read two 3 by 3 matrix and find out their sum and display result?
i tried this but i got Runtime error
Scanner r=new Scanner(System.in);
int [][]array = null;
int[][]array2 = null;
int total=0;
System.out.println("Enter matrix");
for(int row=0;row<array.length;row++){
for(int col=0;col<array[row].length;col++){
array[row][col]=r.nextInt();
array[row][col]=r.nextInt()
;
System.out.print(" "+total +" ");
total=array[row][col]+array2[row][col];
System.out.println(" ");
You are not allocating any memory for the array references, they are referencing nothing(null)... Try:
int[][] array = new int[3][3];
int[][] array2 = new int[3][3];
Also, you are missing a semi-colon in 9th line of your code.Also,in same line, I believe it should be array2 & not array.
The first FOR-Loop demonstrates how to input values in the arrays. This code will require that the user inputs the values of both arrays simultaneously.
The second FOR-Loop demonstrates how to sum the values of each array. Later, both arrays are added together.
//Since you know the the array will be 3x3,
//declare it!
int[][] array1 = new int[3][3];
int[][] array2 = new int[3][3];
int array1Total = 0;
int array2Total = 0;
int endResult;
for (int x = 0; x < array1.length; x++) {
for (int y = 0; y < array1[x].length; y++) {
array1[x][y] = r.nextInt();
array2[x][y] = r.nextInt();
}
}
for (int x = 0; x < array1.length; x++) {
for (int y = 0; y < array1[x].length; y++) {
array1Total += array1[x][y];
array2Total += array2[x][y];
}
}
endResult = array1Total + array2Total;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.