java 如何在Kotlin(版本1.6.0)中解决此内存错误

62lalag4  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(156)

我正在尝试从用户那里获取一组跳棋游戏的移动。我是Kotlin的新手,记忆有问题。代码是:

fun promtUser(): Pair<Pair<Int, Int>, Pair<Int, Int>> {

    print("Enter move (ex. '3,2 to 4,3'): ")
    
    var input: String? 
    var match: MatchResult? = null
    while (match == null) {
        
        input = readLine()?.trim() ?: ""
        match = "\\s*(\\d+),(\\d+)\\s+to\\s+(\\d+),(\\d+)\\s*".toRegex().matchEntire(input ?: "")
        if (match == null) {
            println("Invalid input. Please enter a move in the format 'row,column to row,column'.")
        }
    }
    val (fromRow, fromCol, toRow, toCol) = match.destructured.toList().map { it.toInt() }
    val from = Pair(fromRow - 1, fromCol - 1)
    val to = Pair(toRow - 1, toCol - 1)

    return from to to
    
}

我将其命名为:

val (from, to) = promtUser()

错误消息为:

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "pool-1-thread-1"

Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"
oknwwptz

oknwwptz1#

我现在也在学习Kotlin。我不确定你的内存不足错误是语言还是你的特定安装的问题。但我知道正则表达式在任何编程语言中都可能有问题。或者正如一个朋友所说,正则表达式代码是“WORNA”(写一次,再也不读了)。
您解析a,b to x,y的问题似乎可以通过使用splittoIntOrNull的类似代码行数来解决。

fun promptUser(): Pair<Pair<Int, Int>, Pair<Int, Int>> {

    var fromRow : Int? = null
    var fromCol : Int? = null
    var toRow : Int? = null
    var toCol : Int? = null

    print("Enter move (ex. '3,2 to 4,3'): ")

    while (fromRow == null || fromCol == null || toRow == null || toCol == null) {

        val input = readLine()?.trim() ?: ""

        val firstSplit = input.split("to") // change to .split(" to ") if you want to enforce spacing
        if (firstSplit.size == 2) {
            val leftSide = firstSplit[0].split(",")
            val rightSide = firstSplit[1].split(",")

            if ((leftSide.size == 2) && (rightSide.size == 2)) {
                fromRow = leftSide[0].trim().toIntOrNull()
                fromCol = leftSide[1].trim().toIntOrNull()
                toRow = rightSide[0].trim().toIntOrNull()
                toCol = rightSide[1].trim().toIntOrNull()
            }
        }
        if (fromRow == null || fromCol == null || toRow == null || toCol == null) {
            println("Invalid input. Please enter a move in the format 'row,column to row,column'.")
        }
    }

    val fromPoint = Pair(fromRow - 1, fromCol - 1)
    val toPoint = Pair(toRow - 1, toCol - 1)

    return fromPoint to toPoint
}

我不知道这是否解决了你的问题,但我从阅读问题中学到了一些东西。

相关问题