我有一个任务,需要在Scala中连续开发N。对于板的表示,我想遍历2d数组并打印X'en O's。这是该代码:
override def toString(): String = {
val repres = ""
for (rowIndex <- 0 until board.length - 1) {
for (columnIndex <- 0 until board(rowIndex).length - 1) {
if (board(rowIndex)(columnIndex) == Player.Player1) {
repres + "X"
} else if (board(rowIndex)(columnIndex) == Player.Player2) {
repres + "O"
} else if (board(rowIndex)(columnIndex) == Player.NoPlayer) {
repres + "_"
} else {
throw new IllegalArgumentException
}
}
repres + Properties.lineSeparator
}
repres
}
这是木板:
var board = Array.fill[Player](rows,columns) {Player.NoPlayer}
由于某些原因,即使在调试中board.length为6,它也不会通过for循环。
我是scala的新手,所以可能有一些很明显的错误,我只是没有发现。
感谢您的帮助
答案 0 :(得分:3)
I think the problem is not the loop. Are you expecting repres
to change?
You have declared repres
as an immutable String
. All the operations you are doing are pretty much futile, it is creating a new String in each branch but you are not assigning it to anything. The last statement returns repres
as an empty String
.
Try to change the declaration to var repres
.
Then each of the branches needs to change to repres = repres + "X"
etc.
Note that this is not really functional. It's just Java adapted to Scala syntax.
答案 1 :(得分:2)
您不应使用可变变量。它们使代码的可读性降低,并且难以推理,并且可能潜在地制造许多难以调试的问题。
在Scala中有95%的用例中,您不需要可变状态,因此我的建议是,您只是假装它根本不存在,直到您对语言有足够的了解以能够明确地区分其他5种语言为止%的案例。
val repres = board.flatten.map {
case Player.Player1 => "X"
case Player.Player2 => "O"
case _ => "_"
}.mkString
.grouped(board.length)
.mkString(Properties.lineSeparator)