【问题标题】:Java array sum of specific row特定行的Java数组总和
【发布时间】:2013-10-29 11:21:05
【问题描述】:

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

【问题讨论】:

  • 你有两个不同的总和。一个是 int,另一个是 int 数组。
  • 嗯,因为你的print方法调用被注释掉了?
  • 在 main 方法中,您没有调用任何计算和打印总和的函数

标签: java arrays parameters parameter-passing


【解决方案1】:

试试

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);
    }
}

【讨论】:

  • 谢谢!您的解决方案回答了我的两个问题。我是 java 新手,所以这很有帮助!
【解决方案2】:

试试这个代码

       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);
}

【讨论】:

    【解决方案3】:

    这就是你要找的东西,如果我误解了你的疑问,请纠正我。

     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);
            }
    
          }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2023-03-27
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 2017-12-07
      相关资源
      最近更新 更多