java 查找二维数组中所有元素的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36464706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the sum of all elements in a 2D array
提问by Gendarme
Trying to create a 2D array that will find the sum of all elements. I am not inputting my numbers into the 2D array since I am using a driver to check my work. So far I have this - however it will not complie. What am I doing wrong?
试图创建一个二维数组,它将找到所有元素的总和。我没有将我的数字输入到二维数组中,因为我正在使用驱动程序来检查我的工作。到目前为止,我有这个 - 但是它不会遵守。我究竟做错了什么?
public static double sum2d (double[ ][ ] array2d)
{
int sum = 0;
for (int row=0; row < array2d.length; row++)
{
for (int col=0; col < array2d[row].length; col++)
{
sum = sum + array2d [row][col];
}
}
return sum;
}
回答by Gendarme
Your method is declared to return a double
but you are returning sum
which is an int
.
您的方法被声明为返回一个,double
但您返回的sum
是一个int
。
Edit:As @samrap stated in the comments, your code has formatting errors here. You are missing an opening brace {
.
编辑:正如@samrap 在评论中所述,您的代码在此处存在格式错误。你缺少一个左括号{
。
回答by Paul Boddington
You are missing a brace after the method signature
方法签名后缺少大括号
public static double sum2d (double[ ][ ] array2d) { <----- put that in.
Also, you need to declare sum
as double
.
此外,您需要声明sum
为double
.
double sum = 0;
Note that if a method returns double
, and sum
has type int
, you cando return sum
. The problem here is that sum + array2d [row][col];
is a double
so can't be assigned back to an int
without a cast (but that's not what you want to do).
请注意,如果方法返回double
并sum
具有类型int
,则可以执行return sum
。这里的问题是,sum + array2d [row][col];
是一double
所以不能被分配回到一个int
没有投(但是这不是你想要做什么)。
回答by Divz
Declare sum as double instead of int
将 sum 声明为 double 而不是 int
回答by ozkan cil
package Homeworks;
打包作业;
public class HomeWork86 { public static void main(String[] args) {
公共类 HomeWork86 { public static void main(String[] args) {
int[][] a = {
{1,1,2},
{3,1,2},
{3,5,3},
{0,1,2}
};
int sum=0;
for (int i=0; i<a.length;i++){
for (int j=0;j<a[i].length;j++){
sum+=a[i][j];
}
System.out.println(sum);
sum=0;
}
} }
} }