将2个数组加在一起并返回它的总和 [英] Adding 2 arrays together and return the sum of it

查看:91
本文介绍了将2个数组加在一起并返回它的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将2个数组加在一起并返回它的总和,但它不会运行。我想知道为什么?







I am trying to add 2 arrays together and return the sum of it, but it doesn't run. I wonder why?



public class MyProgram
{
    public static void main (String[] args)
    {
        new MyProgram().start();
    }

    public void start()
    {
        int[] ar1 = {3, 8, 4, 9, 5, 5, 23, 14};
        int[] ar2 = {33, 23, 41, 9, 17, 51, 23, 45};

        sumA(ar1, ar2);
    }

    private int[] sumA(int[] ar1, int[] ar2)
    {
        int[] sumArray = new int[0];

        for (int i = 0; i < ar1.length; i++)
        {
            sumArray[i] = ar1[i] + ar2[i];
        }
        return sumArray;
    }
}

推荐答案

我敢打赌它。

我也打赌它没有做任何事 - 因为你没有告诉它 任何东西。

即使它总结了你的两个阵列,你也不使用结果,所以你无法找到它是否得到了正确的结果!



从调试器开始:在你的第一行放一个断点code> main 方法,并逐步完成整个程序。它应该是相当明显的,它不会做什么 - 但它不会向你显示任何结果,除非你明确告诉它 - 以及确切显示的结果!
I bet it does.
I also bet it does nothing - because you haven't told it to do anything.
Even if it summed your two arrays, you don't use the result, so you have no way of finding out if it got the correct result anyway!

Start with the debugger: put a breakpoint on the first line in your main method, and step your way through the program. It should be fairly obvious what it is and isn't doing - but it isn't going to show you any result unless you specifically tell it to - and exactly what results to show!


如果要对两个数组求和,则需要遍历两个数组的字段(伪代码):

If you want to sum both arrays, you need to loop through the fields of both arrays (pseudo code):
int SumOfArray = 0;
for (i = array1.LowerBound; array1.UpperBound; i++)
{
    SumOfArray = SumOfArray + array1[i];
}

for (i = array2.LowerBound; array2.UpperBound; i++)
{
    SumOfArray = SumOfArray + array2[i];
}

Return SumOfArray;





但是更容易使用 Coollection [ ^ ]或 Lambda表达式 [ ^ ],提供与Linq类似的功能。



But much, much easier is to use Coollection[^] or Lambda Expressions[^], which provide functionality similar to Linq.


我会指出这个bug,你试着解决它:

首先,你已经声明了一个零元素数组

I will point out the bug, and you try to fix it:
First of all, you have declared a zero element array
int[] sumArray = new int[0];



没有 l 在ar1找到属性,在这里看错字


There is no length property in ar1, watch typo here

ar1.length


这篇关于将2个数组加在一起并返回它的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆