Java 定义一个4行4列的double 型二维数组,并创建一个方法显示数组,计算任意给定的行,给定的列,主对角线和副对角线的和以及数组中的最大值
时间: 2023-12-03 10:45:00 浏览: 172
可以按照以下方式定义一个4行4列的double型二维数组:
```java
public class ArrayExample {
private static double[][] array = new double[4][4];
public static void main(String[] args) {
initArray();
displayArray();
double rowSum = getRowSum(1);
System.out.println("The sum of row 1 is: " + rowSum);
double colSum = getColSum(2);
System.out.println("The sum of column 2 is: " + colSum);
double mainDiagonalSum = getMainDiagonalSum();
System.out.println("The sum of main diagonal is: " + mainDiagonalSum);
double subDiagonalSum = getSubDiagonalSum();
System.out.println("The sum of sub diagonal is: " + subDiagonalSum);
double max = getMax();
System.out.println("The max value in the array is: " + max);
}
private static void initArray() {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = Math.random() * 10;
}
}
}
private static void displayArray() {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
}
private static double getRowSum(int row) {
double sum = 0;
for (int j = 0; j < array[row].length; j++) {
sum += array[row][j];
}
return sum;
}
private static double getColSum(int col) {
double sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i][col];
}
return sum;
}
private static double getMainDiagonalSum() {
double sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i][i];
}
return sum;
}
private static double getSubDiagonalSum() {
double sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i][array.length - 1 - i];
}
return sum;
}
private static double getMax() {
double max = Double.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] > max) {
max = array[i][j];
}
}
}
return max;
}
}
```
以上代码中,initArray() 方法用于初始化数组,displayArray() 方法用于显示数组,getRowSum() 和 getColSum() 方法分别用于计算给定行和给定列的和,getMainDiagonalSum() 和 getSubDiagonalSum() 方法分别用于计算主对角线和副对角线的和,getMax() 方法用于计算数组中的最大值。
示例输出:
```
3.914473250670139 2.2716796700022865 7.37167507828722 8.114215635193565
2.580699050997793 8.708102348565188 4.164327307623968 7.986300919297015
0.9892857347916791 4.246921640813247 3.113938437042041 2.9468401345122977
8.474400235712217 1.9783331824303322 5.033605087198085 3.502797117153266
The sum of row 1 is: 23.559429626488964
The sum of column 2 is: 19.57854591315131
The sum of main diagonal is: 19.757454722970637
The sum of sub diagonal is: 21.74317218464671
The max value in the array is: 8.708102348565188
```
阅读全文