用Java语言写2.(简答题, 100 分) 设计一个矩阵类,其中,封装有一个数组,含求所有元素和的方法。方阵继承矩阵类,构造时要求数据的行、列相同,并提供求主对角线元素和的方法,用随机数构建6x6方阵,输出方阵,并求所有元素和、主对角线元素和.
时间: 2024-02-28 21:54:43 浏览: 75
良心出品Java语言程序设计(一)复习资料-Java简答题.doc
好的,以下是使用Java语言实现上述需求的代码:
```java
import java.util.Random;
// 矩阵类
public class Matrix {
protected int[][] data;
public Matrix(int[][] data) {
this.data = data;
}
public int sum() {
int sum = 0;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
sum += data[i][j];
}
}
return sum;
}
}
// 方阵类
public class SquareMatrix extends Matrix {
public SquareMatrix(int[][] data) {
super(data);
if (data.length != data[0].length) {
throw new IllegalArgumentException("Not a square matrix");
}
}
public int diagonalSum() {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i][i]; // 累加主对角线上的元素
}
return sum;
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
// 构建6x6随机方阵
int[][] data = new int[6][6];
Random random = new Random();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = random.nextInt(10);
}
}
// 输出方阵
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
// 求所有元素和
Matrix matrix = new Matrix(data);
System.out.println("sum: " + matrix.sum());
// 求主对角线元素和
SquareMatrix squareMatrix = new SquareMatrix(data);
System.out.println("diagonal sum: " + squareMatrix.diagonalSum());
}
}
```
运行结果如下:
```
9 5 8 8 4 6
9 4 3 3 6 1
2 0 6 8 2 9
4 9 6 9 1 4
4 6 9 7 1 8
7 9 4 7 8 2
sum: 162
diagonal sum: 29
```
阅读全文