本文介绍了如何在Java中设计一个矩阵类,该类包含一个二维数组并实现了计算所有元素之和的方法。同时,创建了一个子类,要求矩阵的行数和列数相等,并添加了计算主对角线元素和的功能。通过随机数生成3x4的方阵
时间: 2024-10-25 21:12:29 浏览: 43
在Java中设计矩阵类,首先我们可以创建一个名为Matrix的基础类,它包含两个维度的数组(二维列表),表示矩阵的元素。例如:
```java
public class Matrix {
private int[][] elements;
public Matrix(int rows, int cols) {
elements = new int[rows][cols];
}
// 计算矩阵所有元素的总和
public int sumAll() {
int total = 0;
for (int[] row : elements) {
for (int element : row) {
total += element;
}
}
return total;
}
// 其他方法如获取/设置元素、打印矩阵等...
}
```
然后为了满足特定需求,比如当矩阵的行数和列数相等时,可以创建一个子类SquareMatrix:
```java
public class SquareMatrix extends Matrix {
public SquareMatrix(int size) {
super(size, size);
}
// 添加计算主对角线元素和的方法
public int sumDiagonal() {
int sum = 0;
for (int i = 0; i < getSize(); i++) {
sum += elements[i][i];
}
return sum;
}
// 获取矩阵大小
public int getSize() {
return elements.length;
}
}
// 使用示例
public static void main(String[] args) {
SquareMatrix squareMat = new SquareMatrix(3);
for (int i = 0; i < squareMat.getSize(); i++) {
for (int j = 0; j < squareMat.getSize(); j++) {
squareMat.elements[i][j] = (int)(Math.random() * 10); // 随机填充整数
}
}
System.out.println("矩阵所有元素的总和: " + squareMat.sumAll());
System.out.println("主对角线元素的和: " + squareMat.sumDiagonal());
}
```
阅读全文
相关推荐


















