我正在尝试为一个二维数组编写迭代器。以下是我想出的代码。
当运行上述代码时,会跳过第一行,并在打印所有元素后出现
谢谢, Siddharth Raina.
def rowsTest() {
val array = Array(
Array(9, 11, 4, 89),
Array(7, 62, 34, 2),
Array(3, 4, 5, 12),
Array(13, 4, 5, 12),
Array(3, 24, 5, 12),
Array(3, 4, 35, 12)
)
def rows: Iterator[Iterator[Int]] = {
new Iterator[Iterator[Int]] {
private var rowIndex = 0
def hasNext: Boolean = rowIndex < 6
def next: Iterator[Int] = {
val rowIterator = new Iterator[Int] {
private var columnIndex = 0
def next: Int = {
val p = array(columnIndex)(rowIndex)
columnIndex += 1
println("ColIndex = "+ columnIndex.toString)
p
}
def hasNext: Boolean = columnIndex < 4
}
rowIndex += 1
println("RowIndex = "+ rowIndex.toString)
rowIterator
}
}
}
for(row <- rows; elem <- row)
println(elem)
}
当运行上述代码时,会跳过第一行,并在打印所有元素后出现
ArrayIndexOutOfBoundsException
。你能帮我找出问题出在哪里吗?谢谢, Siddharth Raina.