我正在尝试迭代for循环但是当我尝试从2D数组中获取值并添加该值然后循环行为异常。这是我正在分享的代码......
var max_sum = 0
var total : Int = 0
val arr = Array(6) { IntArray(6) }
for (arr_i in 0..5) {
for (arr_j in 0..5) {
arr[arr_i][arr_j] = arr_i*arr_j
}
}
if (arr.size <= 3 || arr[0].size <= 3) {
print("not valid array")
Log.e("total sum","not valid array")
} else {
for (row in 1..arr.size - 1) {
for (col in 1..arr[0].size - 1) {
total = arr[row][col] +
arr[row - 1][col] +
arr[row - 1][col - 1] +
arr[row + 1][col + 1] +
arr[row + 1][col] +
arr[row + 1][col - 1] +
arr[row + 1][col + 1]
}
max_sum = Math.max(max_sum, total)
}
print(max_sum)
Log.e("total sum",""+max_sum)
}
答案 0 :(得分:0)
我在kotlin中使用了直到inbulid方法,提供了for循环中使用的方法来迭代数组并获得总和值。
var max_sum = 0
var total : Int = 0
val arr = Array(6) { IntArray(6) }
for (arr_i in 0..5) {
for (arr_j in 0..5) {
arr[arr_i][arr_j] = arr_i*arr_j
}
}
if (arr.size <= 3 || arr[0].size <= 3) {
print("not valid array")
Log.e("total sum","not valid array")
} else {
for (row in 1 until arr.size -1 ) {
for (col in 1 until arr[0].size-1) {
total = arr[row][col] +
arr[row - 1][col] +
arr[row - 1][col - 1] +
arr[row + 1][col + 1] +
arr[row + 1][col] +
arr[row + 1][col - 1] +
arr[row + 1][col + 1]
}
max_sum = Math.max(max_sum, total)
}
print(max_sum)
Log.e("total sum",""+max_sum)
}
答案 1 :(得分:0)
for (row in 1..arr.size - 1) {
for (col in 1..arr[0].size - 1) {
total = arr[row][col] +
arr[row - 1][col] +
arr[row - 1][col - 1] +
arr[row + 1][col + 1] +
arr[row + 1][col] +
arr[row + 1][col - 1] +
arr[row + 1][col + 1]
}
索引迭代到上限大小 - 1, index + 1超出