gpt4 book ai didi

eclipse - "Exception in thread "main "java.util.NoSuchElementException: head of empty list "error and more in Scala

转载 作者:行者123 更新时间:2023-12-03 20:49:48 26 4
gpt4 key购买 nike

我写了一个递归括号平衡函数,代码中似乎没有任何错误,但是当我运行它时却出现了很多错误。

我用这样的调用编写了函数:

if(balance("blarg(arg)".toList)) println("true!") else println("false")

和这样的定义:

def balance(chars: List[Char]): Boolean ={

implicit class MutableInt(var value: Int)
{
def inc() = { value+=1 }
def dec() = { value-=1 }
}

var stack: Int = 0

def recursbalance(chars: List[Char], stack: Int): Boolean=
{

if ((chars.head: Char) == "(".toList) stack.inc()
else if ((chars.head: Char) == ")".toList) stack.dec()

if (stack<0) false

if (chars.isEmpty: Boolean) if (stack == 0) true else false

recursbalance(chars.tail: List[Char], stack: Int)

}
recursbalance(chars: List[Char], stack: Int)
}

我遇到了这些错误:

Exception in thread "main" java.util.NoSuchElementException: head of empty list
at scala.collection.immutable.Nil$.head(List.scala:337)
at scala.collection.immutable.Nil$.head(List.scala:334)
at recfun.Main$.recursbalance$1(Main.scala:45)
at recfun.Main$.balance(Main.scala:55)
at recfun.Main$.main(Main.scala:16)
at recfun.Main.main(Main.scala)

我该如何解决?抱歉,我是 Scala 的新手。

我试着用这个替换我的递归调用:

   if (chars.isEmpty: Boolean) {
if (stack == 0) true else false
}
else
recursbalance(chars.tail: List[Char], stack: Int)

但我仍然得到所有的错误..

最佳答案

在调用 head 之前,您需要检查您的 List 是否为空,match 可能是执行此操作的最佳方法:

  def balance(chars: List[Char]) = {

def recursbalance(chars: List[Char], stack: Int): Int = chars match {
case Nil => stack
case ')' :: tail => recursbalance(tail, stack - 1)
case '(' :: tail => recursbalance(tail, stack + 1)
case x :: tail => recursbalance(tail, stack)
}
recursbalance(chars, 0) == 0;
}

我已经稍微改变了你的方法来删除 MutableInt 并直接在内部使用 Int

我进行了快速检查:

  println(balance("())".toList));
println(balance("(())".toList));

输出

false
true

关于eclipse - "Exception in thread "main "java.util.NoSuchElementException: head of empty list "error and more in Scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15707142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com