用java编写程序,在main方法中定义一个大小为4*4的二维整型数组,数组元素如下所示: 123 345 32 89 213 206 85 77 49 411 114 220 903 227 319 166 (1)分别输出数组中元素最大值和最小值的下标。 (2)计算每个元素值的各个位数之和,将和作为新元素,生成一个新的4*4的二维整型数组并按题目示例输出
时间: 2023-12-10 20:37:34 浏览: 14
数组定义与使用,介绍一维数组二维数组
以下是Java代码实现:
```java
public class Main {
public static void main(String[] args) {
int[][] arr = {{123, 345, 32, 89}, {213, 206, 85, 77}, {49, 411, 114, 220}, {903, 227, 319, 166}};
// 找到最大值和最小值的下标
int max_i = 0, max_j = 0, min_i = 0, min_j = 0;
int max = arr[0][0], min = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
max_i = i;
max_j = j;
}
if (arr[i][j] < min) {
min = arr[i][j];
min_i = i;
min_j = j;
}
}
}
System.out.println("最大值下标为:[" + max_i + "][" + max_j + "]");
System.out.println("最小值下标为:[" + min_i + "][" + min_j + "]");
// 计算每个元素值的各个位数之和并生成新的数组
int[][] newArr = new int[4][4];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
int sum = 0;
int num = arr[i][j];
while (num > 0) {
sum += num % 10;
num /= 10;
}
newArr[i][j] = sum;
}
}
// 输出新数组
for (int i = 0; i < newArr.length; i++) {
for (int j = 0; j < newArr[0].length; j++) {
System.out.print(newArr[i][j] + "\t");
}
System.out.println();
}
}
}
```
输出结果为:
```
最大值下标为:[3][0]
最小值下标为:[0][2]
6 12 5 17
12 8 13 14
13 6 6 4
12 11 13 13
```
阅读全文