我正在尝试获取第2行的总和。我的代码编译但不打印任何内容。一些指导? 另外,在第一个问题的基础上,我将如何访问第3列中的最大元素?
import java.util.*;
public class TestCode {
public static void main(String[] args) {
int array[][] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
int sum = 0;
//print(array);
}
public static void print(int list[][]) {
for(int row = 0; row < list.length;row++) {
int[] sum = new int [3];
for(int column = 0; column < list[row].length; column++) {
sum[1] = list.length;
}
System.out.println(sum);
}
}
}
答案 0 :(得分:0)
试
public class Test {
public static void main(String[] args) {
int array[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
FindLargestInColumn(array, 2);
FindSumforRow(array,2);
}
public static void FindLargestInColumn(int list[][], int index) {
int largest = -1;
for (int[] row : list) {
if (row[index] > largest)
largest = row[index];
}
System.out.println("The Largest value in column " + (index )+ " is " + largest);
}
public static void FindSumforRow(int list[][], int rowIndex) {
int sum = 0;
int[] row = list[rowIndex];
for (int value : row) {
sum = sum + value;
}
System.out.println("The Sum of value in row " + (rowIndex)+ " is " + sum);
}
}
答案 1 :(得分:0)
试试这段代码
public static void print(int list[][]) {
int sum = 0;
int arrSum[] = new int[3];
for (int column = 0; column < list[1].length; column++) {
arrSum[column] = list[1][column];
sum += list[1][column];
}
System.out.println("array " + Arrays.toString(arrSum) + " sum =" +sum);
}
答案 2 :(得分:0)
这就是你要找的,如果我误解了你的疑问,请纠正我。
public static void main(String[] args) throws UnknownHostException {
int array[][] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
int sum = 0;
print(array,2); // 2 here is rowNumber, can be replaced with other no
}
public static void print(int list[][], int rowNumber) {
for(int row = 0; row < list.length;row++) {
int sum =0;
if(row == (rowNumber-1)){
for(int column = 0; column < list[row].length; column++) {
sum += list[row][column];
}
System.out.println(sum);
}
}
}