用int []添加int

瑞安·范·杜森(Ryan Van Dusen)
 int sum = 0;   

      for (int i = 0; i < counts.length; i++)      
      {
            sum = sum + counts[i];  //doesnt work says + bad operator  first type int second type int[]

      } 
      return sum;

我以为这可以用,但是我不能做些什么呢?

public static void main(String[] args) {
int[][] counts =
     {
        { 1, 0, 1 },
        { 1, 1, 0 },
        { 0, 0, 1 },
        { 1, 0, 0 },
        { 0, 1, 1 },
        { 0, 1, 1 },
        { 1, 1, 0 }
     };
  int sum = ArrayUtil.rowSum(counts, 5);
  System.out.println(sum);
  System.out.println("Expected: 2");

  int[][] magicSquare = {
     { 16, 3, 2, 13 },
     { 5, 10, 11, 8 },
     { 9, 6, 7, 12 },
     { 4, 15, 14, 1 },
  };

  for (int row = 0; row <= 3; row++)
  {
     System.out.println(ArrayUtil.rowSum(magicSquare, row));
     System.out.println("Expected: 34");
  }
}
  public static int rowSum(int[][] counts, int row) 
  {   
      int sum = 0;   

      for (int i = 0; i < counts.length; i++)      
      {
            sum = sum + counts[i];    

      } 
      return sum;
  }

添加了我拥有的完整代码。预先感谢您的任何帮助。它不起作用,因为counts [i]是2d数组的一部分吗?

shmosel

如果您尝试对2D数组的一行进行求和,则您的方法应如下所示:

public static int rowSum(int[][] counts, int row) {
    int sum = 0;
    for (int count : counts[row]) {
        sum += count;
    }
    return sum;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章