nz_*_*_21 7 arrays getter-setter kotlin
这是代码。
val stack = Array(inputString.length + 1) { "" }
var current = 0
for ((i, char) in inputString.withIndex()) {
if (char == '(') {
current += 1
continue
} else if (char == ')') {
val enclosedString = stack[current]
stack[current - 1] = stack[current - 1] + enclosedString.reversed()
current -= 1
continue
} else {
stack[current] += char //here's the compile time error
}
}
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息“没有设置方法提供数组访问”。我不明白这个。
如果我将其更改为:
stack[current] = stack[current] + char
Run Code Online (Sandbox Code Playgroud)
一切正常。
为什么会这样?
错误的原因是Char变量分配给 an的错误Array<String>,您需要将 the 转换Char为Stringbefore,这就是语句中发生的情况
stack[current] = stack[current] + char
Run Code Online (Sandbox Code Playgroud)
该+函数返回一个新的String连接右侧的字符串表示形式(即它自动调用toString右侧的操作数)。换句话说,它是在转换Char变量char到String级联之前。
你也可以自己转换。
stack[current] += char.toString()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6929 次 |
| 最近记录: |