int sum = 0;
for (int i = 0; i < counts.length; i++)
{
sum = sum + counts[i]; //doesnt work says + bad operator first type int second type int[]
}
return sum;
我认为这样可行,但我无法做些什么才能让它发挥作用?
public static void main(String[] args) {
int[][] counts =
{
{ 1, 0, 1 },
{ 1, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 0 },
{ 0, 1, 1 },
{ 0, 1, 1 },
{ 1, 1, 0 }
};
int sum = ArrayUtil.rowSum(counts, 5);
System.out.println(sum);
System.out.println("Expected: 2");
int[][] magicSquare = {
{ 16, 3, 2, 13 },
{ 5, 10, 11, 8 },
{ 9, 6, 7, 12 },
{ 4, 15, 14, 1 },
};
for (int row = 0; row <= 3; row++)
{
System.out.println(ArrayUtil.rowSum(magicSquare, row));
System.out.println("Expected: 34");
}
}
public static int rowSum(int[][] counts, int row)
{
int sum = 0;
for (int i = 0; i < counts.length; i++)
{
sum = sum + counts[i];
}
return sum;
}
添加了我的完整代码。非常感谢anyhelp。 是不行,因为count [i]是2d数组的一部分?
答案 0 :(得分:1)
counts
是一个多维数组,因此您需要迭代内部数组中包含的值以获取sum
。使用可能类似的for-each
loops,
int sum = 0;
for (int[] array : counts) { // <-- for each array in counts
for (int value : array) { // <-- for each value in the array
sum += value; // <-- add the value to the sum
}
}
将相同的循环结构应用于rowSum
,我们可能会得到
public static int rowSum(int[][] counts, int row) {
int sum = 0;
for (int value : counts[row]) {
sum += value;
}
return sum;
}
或使用Java 8+ IntStream
之类的
public static int rowSum(int[][] counts, int row) {
return IntStream.of(counts[row]).sum();
}
答案 1 :(得分:1)
如果您尝试对2D数组的单行求和,则您的方法应如下所示:
public static int rowSum(int[][] counts, int row) {
int sum = 0;
for (int count : counts[row]) {
sum += count;
}
return sum;
}
答案 2 :(得分:0)
counts
是int
的二维数组(即int[][]
)您无法将int[]
添加到int
。
如果要对counts
的值求和,请考虑以下代码:
int sum = 0;
for(int i = 0; i < counts.length; i++) {
for(int j = 0; j < counts[i].length; j++) {
sum += counts[i][j];
}
}
答案 3 :(得分:0)
我用递归做了这个,因为每个人都发布了他们自己的答案,所以我做了这种递归方式。
let imageData = UIImageJPEGRepresentation(imageToPost.image!, 0.1)
let imageFile = PFFile(name: "image.png", data: imageData!)
希望您的答案有用。