Java方法总和任意数量的int [英] Java method to sum any number of ints
本文介绍了Java方法总和任意数量的int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个java方法 sumAll()
,它接受任意数量的整数并返回它们的总和。
I need to write a java method sumAll()
which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
我不知道该怎么做。
推荐答案
您需要:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
然后调用方法并根据需要为其提供尽可能多的int值: / p>
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
这篇关于Java方法总和任意数量的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文