gpt4 book ai didi

arrays - 如何在Kotlin上实现readLine()!!。toIntArray()?

转载 作者:行者123 更新时间:2023-12-02 13:14:22 26 4
gpt4 key购买 nike

我想实现一个功能或从控制台顺序存储数组的某种方式。像这样:readLine()!!.toIntArray()

Would it be convenient to use a loop for this or could it be avoided?



然后,您可以使用数组的索引访问它们。
fun main(args: Array<String>) {
myFunction()
}

答:
fun myFunction() {
println(" . First number: ")
val num1:Float = readLine()!!.toFloat()
println(" . Second number: ")
val num2:Float = readLine()!!.toFloat()
println(" . Third number: ")
val num3:Float = readLine()!!.toFloat()
println(" . Fourth number: ")
val num4:Float = readLine()!!.toFloat()

val result:Float = (num1+num2) + (num3*num4)
print("The result is: $result")
}

B:
fun myFunction() {
println("Enter four numbers ...")
// val numbers:IntArray = intArrayOf(45, 22, 10, 13)
val numbers:IntArray = readLine()!!.toIntArray() //HERE: toIntArray() isn't defined

val result:Int = (numbers[0]+numbers[1]) + (numbers[2]*numbers[3])
print("The result is: $result")
}

定义数组时,我必须指出要从控制台读取的值的数量,即数组的大小。

Or is there another way to stop reading data in the console?



简而言之,我想从A块转向B块。


println("Enter four numbers ...")
val numbers = readLine()!!.split(" ").map { it.toInt() }

val result:Int = (numbers[0]+numbers[1]) + (numbers[2]*numbers[3])
print("The result is: $result")

最佳答案

您不需要循环。可以用map完成:

val numbers = readLine()!!.split(" ").map { it.toInt() }

关于arrays - 如何在Kotlin上实现readLine()!!。toIntArray()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47827229/

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