Scala 更新数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9384817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala updating Array elements
提问by user1224307
I never thought I would be asking such a simple question but how do I update array element in scala
我从没想过我会问这么简单的问题,但是如何在 Scala 中更新数组元素
I have declared inner function inside my Main object and I have something like this
我已经在我的 Main 对象中声明了内部函数,我有这样的东西
object Main
{
def main(args: Array[String])
{
def miniFunc(num: Int)
{
val myArray = Array[Double](num)
for(i <- /* something*/)
myArray(i) = //something
}
}
}
but I always get an exception, Could someone explain me why and how can I solve this problem?
但我总是遇到例外,有人可以解释我为什么以及如何解决这个问题吗?
回答by dhg
Can you fill in the missing details? For example, what goes where the comments are? What is the exception? (It's always best to ask a question with a complete code sample and to make it clear whatthe problem is.)
你能填写缺失的细节吗?例如,评论在哪里?什么是例外?(它总是最好问一个问题有一个完整的代码示例,并要清楚是什么问题。)
Here's an example of Array construction and updating:
这是数组构造和更新的示例:
scala> val num: Int = 2
num: Int = 2
scala> val myArray = Array[Double](num)
myArray: Array[Double] = Array(2.0)
scala> myArray(0) = 4
scala> myArray
res6: Array[Double] = Array(4.0)
Perhaps you are making the assumption that numrepresents the size of your array? In fact, it is simply the (only) element in your array. Maybe you wanted something like this:
也许您正在假设num代表数组的大小?事实上,它只是数组中的(唯一)元素。也许你想要这样的东西:
def miniFunc(num: Int) {
val myArray = Array.fill(num)(0.0)
for(i <- 0 until num)
myArray(i) = i * 2
}

