java - 如何将多维数组的添加放入同一类中的方法中?
问题描述
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
int [][] matrix1 = new int[ir1][ic1];
int [][] matrix2 = new int[ir2][ic2];
// an example of it is the addition of two matrices put into the method
int total[][] = new int [ir1][ic1];
for (int r = 0; r < matrix1.length; r++) {
for (int c = 0; c < matrix2[r].length; c++)
total [r][c] = matrix1[r][c] + matrix2[r][c];
}
System.out.println("\nThe addition of two Matrices: ");
for (int r = 0; r < total.length; r++) {
for (int c = 0; c < total[r].length; c++)
System.out.printf("%7d", total[r][c]);
System.out.println();
}
// this is where I want to put the addition
public static int [][] add () {
}
解决方案
你几乎拥有它。
但请注意:在 Java 中,方法中不能有其他方法。因此,add()
方法必须在main()
方法之外。
然后你只需要调整参数来接受矩阵并将逻辑移动到方法中:
public static void main(String[] args) {
/* ... */
int ir1 = 5, ic1 = 3, ir2 = 5, ic2 = 3;
int[][] matrix1 = new int[ir1][ic1];
int[][] matrix2 = new int[ir2][ic2];
int[][] total = add (matrix1, matrix2);
/* ... */
}
public static int[][] add (int[][] matrix1, int[][] matrix2) {
int total[][] = new int [matrix1.length][matrix1[0].length];
for (int r = 0; r < matrix1.length; r++) {
for (int c = 0; c < matrix2[r].length; c++) {
total[r][c] = matrix1[r][c] + matrix2[r][c];
}
}
return total;
}
推荐阅读
- sql - 在 SQL 中转换格式为 YYYY-MM-DD HH:MM:SS 的日期、日期和时间戳字符串
- sql - Postgres - 使用 \COPY 强制数字列中的 NULL 值
- r - Rcpp - 从自定义分布生成多个随机观察
- c# - 自动化引擎无法播放测试,因为它无法与桌面交互...但桌面未锁定
- vagrant - Vagrant ssh 在成功启动主机后挂起
- c# - ObservableCollection 刷新视图 MVVM
- r - 使用 lapply 将标签传递给 ggplot2
- c# - C# - 获取源代码文件正在使用或引用的类型列表
- ansible - Ansible 动态清单组不起作用
- c# - 带有关系实体的 LINQ 连接查询