[英]How can I print the sum of the elements in a 2-D array?
Here is what I currently have: 这是我目前拥有的:
final int[][] myArray =
{
{ 1, 2, 5, 4 },
{ 4, 3, 2, 1 },
{ 5, 6, 7, 8 },
{ 8, 7, 6, 5 },
};
PrintArray(myArray);
Analysis(myArray);
}
public static void Analysis(int[][] myArray)
{
for (int i = 0; i < myArray.length; i++)
{
int sum = sum + myArray[i];
}
System.out.println(sum);
}
public static void PrintArray(final int[][] myArray)
{
for (int i = 0; i < myArray.length; i++)
{
for (int j = 0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
And it says, "The operator + is undefined for the argument type(s) int, int[]" at the part with the sum. 它说,“和运算符+对于参数类型int,int []未定义”,位于加和部分。 I am not sure why this would be.
我不确定为什么会这样。
I would use for-each
loops and you need to declare sum
before the loop (so it is visible). 我将使用
for-each
循环 ,您需要在循环之前声明sum
(因此可见)。 And the Java naming conventions would suggest starting with a lower case letter (your method looks like a class). Java命名约定建议以小写字母开头(您的方法看起来像一个类)。
public static void Analysis(int[][] myArray) {
int sum = 0;
for (int[] arr : myArray) {
for (int val : arr) {
sum += val;
}
}
System.out.println(sum);
}
It is a TWO dimensional array. 它是一个二维数组。 How exactly are you expecting to access it using one indexer?
您期望如何使用一个索引器访问它?
You can try this: 您可以尝试以下方法:
public static void Analysis(int[][] myArray)
{
int sum=0; //sum must be initiated BEFORE
for (int i = 0; i < myArray.length; i++)
{
for(int j=0;j<myArray[i].length;j++)
sum += myArray[i][j];
}
System.out.println(sum);
}
Your array has two dimensions! 您的数组有两个维度! Thus you need two loops iterating both of those dimensions!
因此,您需要两个循环来迭代这两个维度!
for (int i....
for (int j=0; j<array[i].length ; j++)
sum += array [i] [j] ;
You know: very much the same way that you already wrote down your code that prints the array! 您知道:几乎与您已经记录了打印数组的代码一样! There is no difference between accessing the array cell for printing.... or for summing them up!
访问阵列单元进行打印...或对其进行汇总之间没有任何区别!
Your "myArray" is a two dimensions, you need two loop for it's operation, like this: 您的“ myArray”是二维的,需要两个循环来进行操作,如下所示:
public static void Analysis(int[][] myArray)
{
for (int i = 0; i < myArray.length; i++)
{
int sum = sum + myArray[i];
}
System.out.println(sum);
}
And if i'm not mistaking, your static int[][] myArray is in the main function(?) i suggest you final int[][] myArray
如果我没有记错的话,则您的静态int [] [] myArray位于主函数(?)中,我建议您
final int[][] myArray
public static void Analysis(int[][] myArray){
int sum=0;
for (int i = 0; i < myArray.length; i++){
for(int j=0; j< myArray[i].length;j++){
sum += myArray[i][j];
}
}
System.out.println(sum);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.