zga*_*r20 2 java arrays scala intellij-idea multidimensional-array
我刚刚开始研究Scala,我决定做一个roguelike让我的脚湿透.我来自Java背景,我在使用Scala Arrays时遇到了麻烦.
当我尝试制作一个水平,我称之为一个房间时,我想象一个二维阵列#作为墙壁.我尝试使用,据我所知,Scala嵌套for循环#在i ||时放置墙角色 j为0,或者当i ||时 j位于数组的末尾.在for循环的括号内,我有temp(i, j) = '#'一个"Expression of type Char doesn't conform to expected type, Nothing"在我的IDE,IntelliJ中给我错误.
我在下面发布了我的代码,如果你可以帮我格式化和/或正确使用我的数组,那就太好了.
class Room
{
val room = generate
def generate: Array[Char] =
{
var temp = Array[Char](10, 10)
for (i: Int <- 0 to temp.length; j: Int <- 0 to temp.length)
{
if (i == 0 || j == 0 || i == temp.length-1 || j == temp.length-1)
temp(i, j) = '#'
}
return temp
}
def print: Unit =
{
for (i <- 0 to 10)
{
var line: String = ""
for (j <- 0 to 10)
{
line += room(i, j)
}
println(line)
}
}
}
Run Code Online (Sandbox Code Playgroud)
var temp = Array[Char](10, 10)创建一个Array包含两个换行符的1维(10表示其在ascii中的值).
你会想要使用var temp = Array.ofDim[Char](10,10).然后,您可以使用temp(i)(j)(而不是temp(i, j))访问单元格.
还要注意for (i <- 0 to 10) {}会导致ArrayIndexOutOfBoundsException.你会想要使用for (i <- 0 until 10) {}.
您也可以使用以下Array.tabulate方法:
// Dummy implementation
scala> def calculateCellValue(i: Int, j: Int) =
if (i == 0 || j == 0 || i == 9 || j == 9) '#' else 'x'
scala> val temp = Array.tabulate(10,10)(calculateCellValue)
temp: Array[Array[Char]] = Array(Array(#, #, #, #, #, #, #, #, #, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, #, #, #, #, #, #, #, #, #))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1881 次 |
| 最近记录: |