1

我试图只得到第 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);
      }
    }
}
4

3 回答 3

2

尝试

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);
    }
}
于 2013-10-21T05:04:31.197 回答
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);
}
于 2013-10-21T05:09:38.200 回答
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);
        }

      }
    }
于 2013-10-21T05:13:58.493 回答