gpt4 book ai didi

arrays - 快速将整数插入数组

转载 作者:行者123 更新时间:2023-11-30 14:10:48 25 4
gpt4 key购买 nike

我对 Swift 还不太了解,有一个问题开始有点烦人。

我只想在二维数组中添加整数,但它总是返回相同的错误代码:“ fatal error :数组索引超出范围”

var arrayVolley = [[Int]]()

init(){
self.arrayVolley = [[]]
}

这是我尝试插入的位置:

func addPoints(score : Int, x : Int, y : Int){

if (score > 11 || score < 0){ //11 will be translated as 10x
println("Error on score value")
}
else {
if (x>6 || y>6){
println("Out of array")
}
else{
arrayVolley[x][y]=score
}
}
}

这是我的主要内容:

var i=0
var j=0
for i in 0...6 {
for j in 0...6{
println("Entrez le score")
var scoreinput=input()
var score = scoreinput.toInt()
distance.addPoints(score!, x: i, y: j)
}
}

非常感谢您提前提供的帮助

最佳答案

尝试使用append将整数添加到数组中,它会自动成为下一个索引。它认为如果从未使用过索引,则会给出错误,例如

var test = [Int]()
test.append(2) // array is empty so 0 is added as index
test.append(4)
test.append(5) // 2 is added as max index array is not [2,4,5]
test[0] = 3 // works because the index 0 exist cause the where more then 1 element in array -> [3,4,5]
test[4] = 5 // does not work cause index for never added with append

或者您以正确的大小初始化数组,但它需要一个大小:

var test = [Int](count: 5, repeatedValue: 0) // [0,0,0,0,0]
test[0] = 3 //[3,0,0,0,0]
test[4] = 5 [3,0,0,0,5]

希望对您有帮助,如果没有请随时评论。

关于arrays - 快速将整数插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31797127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com