我绝对被困住了。任何帮助,将不胜感激。问题问
1。创建两个2维数组/矩阵(随机数,范围为1 -500,其中应将1和500声明为类常量)。两者具有相同的尺寸。
2。打印阵列。
3。调用一个方法对两个矩阵求和。 2个矩阵matrix_1和matrix_2的总和是一个矩阵结果,其中对于每一行r和c列, result_rc =矩阵_1_rc +矩阵_2_rc
4。打印结果矩阵。
我被困在3和4上。部分问题是我不了解3的要求。我是否获得每一行和每一列的总和并将其添加到第二个数组的行和列的总和。第二个问题是我对下一步的工作完全迷失了。
我已经研究了几个小时,尝试了不同的事情。
import java.util.*;
public class Lab12p2 {
public static final int MAX = 500;
public static final int MIN = 1;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of times to run the program");
int start = scan.nextInt();
while (start < 0) {
System.out.println("Error! Should be positive. REENTER");
start = scan.nextInt();
}
// end number of times validation
while (start > 0)// counter loop for how many times to run program {
System.out.println("Enter the size of the 2 arrays");
int SIZE = scan.nextInt();
while (SIZE < 0) {
System.out.println("Error! Should be positive. REENTER");
SIZE = scan.nextInt();
} // size validation
// start of methods
int[][] a = new int[SIZE][SIZE];
int[][] b = new int[SIZE][SIZE];// second array
System.out.println("The first array is ");
System.out.println();
randArray(a, SIZE, SIZE, MIN, MAX);
System.out.println("The second array is ");
System.out.println();
randArray(b, SIZE, SIZE, MIN, MAX);
sum2arrays(a, b, SIZE, SIZE);
start--;
}
public static void randArray(int[][] matrix, int row, int col, int low, int up) {
Random rand = new Random();
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
int random = matrix[r][c] = rand.nextInt(up - low + 1) + low;
System.out.print("\t" + random);
}
System.out.println();
}
}
public static void sum2arrays(int[][] matrix1, int[][] matrix2, int col, int row) {
int sumrow;
int sumtotalrow = 0;
for (int r = 0; r < matrix1.length; r++) {
sumrow = 0;
for (int c = 0; c < matrix1[r].length; c++) {
sumrow = sumrow + matrix1[r][c];
}
sumtotalrow = sumtotalrow + sumrow;
}
// testing
System.out.println("The sum of ALL the elements/row = " + sumtotalrow);
}
}
应该
调用一个方法将两个矩阵求和。 2个矩阵matrix_1
和matrix_2
的总和是一个矩阵结果,其中对于每个row r
和column c
,
result_rc= matrix_1_rc+ matrix_2_rc
(我不知道那是什么意思),然后打印结果矩阵
答案 0 :(得分:0)
public static void sum2arrays(int[][] matrix1, int[][]matrix2,int col,int row)
{
int sumrow;
ArrayList <Integer> three=new ArrayList<Integer>();
for (int r = 0; r < matrix1.length; r++)
{
sumrow = 0;
for (int c = 0; c < matrix1[r].length; c++)
{
three.add( matrix2[r][c] + matrix1[r][c]);
}
}
System.out.println("The matrix result is ");
System.out.println(three);
}