简体   繁体   English

用Java打印出一组数字的总和

[英]Printing out the sum of set of numbers in Java

I'm currently practising with while loops and I'm trying to get my loop to add a set of numbers in range between 1 and 10, I've got the code printing out the numbers but not the sum: can someone help me with this?我目前正在练习 while 循环,我正在尝试让我的循环添加一组 1 到 10 之间的数字,我有代码打印出数字而不是总和:有人可以帮我这个?

 public void AddInArray()
 {
    int index = 0;
    while(index <= 10){
        System.out.println(index);
        index++;
    }

 }

Try this尝试这个

 public void addInArray(int[] arr)
 {
    int index = 0;
    int sum = 0;
    while(index < arr.length){
        System.out.println(index);
        sum += arr[i];
        index++;
    }
    System.out.println(sum);

 }

Now to call it,现在叫它,

int[] arr = {1,2,3,4,5,6,7,8};
addInArray(arr);

So having used the code from the 11thdimension, i adapted it so now it works in my code:因此,使用了第 11 维的代码后,我对其进行了修改,现在它可以在我的代码中使用:

public void AddInArray(int length)
{
    int index = 0;
    int sum = 0;
    while(index <= length){
        System.out.println(index);
        sum += index;
        index++;



    }
    System.out.println(sum);
}

So what this does is:所以它的作用是:

while the index is less than the length, print out the index, it also add the index to the integer known as sum and finally it increments the index by one.当索引小于长度时,打印出索引,它还将索引添加到称为 sum 的整数上,最后将索引加一。 one the loop is finished it then carry's out the other function which is to print out the sum that has been storing the int values.一个循环完成,然后执行另一个功能,即打印出已存储 int 值的总和。 it prints out the numbers from 1-10 and the sum of them 55.它打印出 1-10 的数字和它们的总和 55。

Thanks for the help guys.谢谢你们的帮助。

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

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