简体   繁体   English

编写一个名为 arraySum 的 function,它返回 int 值的二维数组中所有值的总和(作为 int)(Java)

[英]Write a function called arraySum that returns the sum (as an int) of all the values in a two-dimensional array of int values (Java)

I am trying to sum all the int values of a 2D array.我正在尝试对二维数组的所有 int 值求和。 I named it array.我把它命名为数组。 my function is then called arraySum.我的 function 然后被称为 arraySum。 If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.如果 arraySum 是 null,我返回 0。否则,它会经过两个 for 循环,将这些 arrays 的值相加。

int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) { 
    if (array == null) {  // test if the incoming param is null
        return 0;
    } else { 
        for (int i = 0; i < array.length; i++) {  // length of the outer array
            for (int j = 0; j < array[i].length; j++) {  // length of the inner array
                sum += array[i][j];
            }
        }
        return sum;  // moved out of the loop
    }
} 

my error message:我的错误信息:

java.lang.AssertionError: Incorrect result:  expected [-217085] but found [-308126] 


  1. Fixing the method signature is the first step.修复方法签名是第一步。
  2. Then you'll need to fix the null check.然后您需要修复 null 检查。
  3. Then your loops need to check the size of the inner and outer arrays.然后你的循环需要检查内部和外部 arrays 的大小。
  4. Move the return statement.移动返回语句。

Here's the fixed code:这是固定代码:

static int arraySum(int[][] array) {  // fix the signature
    if (array == null) {  // test if the incoming param is null
        return 0;
    } else { 
        int sum = 0;  // you need this in the scope of the method - it will be returned at the end
        for (int i = 0; i < array.length; i++) {  // length of the outer array
            for (int j = 0; j < array[i].length; j++) {  // length of the inner array
                sum += array[i][j];
            }
        }
        return sum;  // moved out of the loop
    }
}

Edit: I've concentrated on just the method now - how you call it is up to you.编辑:我现在只专注于方法 - 你怎么称呼它取决于你。 Please note that the method will not affect any externally defined sum variable.请注意,该方法不会影响任何外部定义的sum变量。 It will return the sum and it's up to the caller to store that value somewhere.它将返回总和,并且由调用者将该值存储在某处。

Avoid using primitive for statement.避免使用原语 for 语句。 See following:请参阅以下内容:

    static int arraySum(int[][] array) {
        int sum = 0;
        if (array == null) return 0;

        for(int[] row: array){
            for(int col : row) {
                sum += col;
            }
        }
        return sum;
    }

Streams can do this too: Streams 也可以这样做:

//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}}; 

//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum(); 

System.out.println(sum);

Picking apart the summing code:拆开求和代码:


Stream.of(array)

Turns the 2D array of type int[][] into a Stream<int[]> .int[][]类型的二维数组转换为Stream<int[]> From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.从这里开始,我们需要 go 更深一层来处理二维数组中的每个子数组,因为 stream 仅流式传输第一维。

So at this point we'll have a stream that contains:所以此时我们将有一个 stream 包含:

  • an int[] array containing {1,2,3}一个包含 {1,2,3} 的 int[] 数组
  • an int[] array containing {4,5}一个包含 {4,5} 的 int[] 数组
  • an int[] array containing {6}一个包含 {6} 的 int[] 数组

.flatMapToInt(IntStream::of)

So far we have a Stream of int[] , still two-dimensional.到目前为止,我们有一个 Stream 的int[] ,仍然是二维的。 Flat map flattens the structure into a single stream of ints. Flat map 将结构扁平化为单个 stream 整数。

flatMapToInt() expands each int[] element of the stream into one or more int values. flatMapToInt()将 stream 的每个int[]元素扩展为一个或多个int值。 IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values. IntStream.of()接受一个数组int[]并将其转换为一个 int stream。将这两个组合起来得到一个 stream 的int值。

After the flattening, we'll have an int stream of:扁平化后,我们将得到一个 int stream 的值:

{1,2,3,4,5,6} {1,2,3,4,5,6}


.sum()

Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.现在我们有一个IntStream ,其中所有元素都从原始二维数组中扩展出来,这只是获取所有值的总和。


Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced.现在是免责声明 - 如果您是 Java 的新手并且了解 arrays,这可能有点太高级了。 I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.我建议学习有关嵌套 for 循环和遍历 arrays 的知识。但了解 API 何时可以为您完成大量工作也很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM