解决 Kotlin 中 BigDecimal 的错误 "Unresolved reference. None of the following candidates is applicable because of receiver type mismatch"

Solving error of BigDecimal in Kotlin "Unresolved reference. None of the following candidates is applicable because of receiver type mismatch"

我在 Android Kotlin

中这样做
val simpleInterest = ((num1*num2)*num3)/100

但是它说 未解决的参考。由于接收器类型不匹配,以下候选 None 是适用的: public inline operator fun BigDecimal.times(other: BigDecimal): kotlin 中定义的 BigDecimal public inline operator fun BigInteger.times(other: BigInteger): BigInteger 在kotlin中定义

其实我的代码是:

fun onSimpleInterest(view: View) {
        val str:String = txtDisplay.text.toString()
        val sp = arrayOf(str.split("[*+\-\/]".toRegex(), 3))
        val num1 = sp[0]
        val num2 = sp[1]
        val num3 = sp[2]
        val simpleInterest = ((num1*num2)*num3)/100
            buttonSI.setOnClickListener {
                txtDisplay.text = simpleInterest

            }

        }

这里发生了一些事情。

split 扩展函数 return 是一个列表。所以 sp 实际上是一个列表数组。

由于 sp 的类型是列表数组,对其进行索引(val num1 = sp[0],等等)实际上是 returning 列表,而不是字符串。所以 num1, num2 和 num3 实际上是 List<String>.

您需要做的是摆脱 arrayOf 并将 sp 设置为 str.split 的结果。 Sp 现在将是一个列表,因此您可以将 num1、num2 和 num3 设置为适当的索引,这将是字符串。

接下来,将这些字符串转换为整数,然后您就可以进行算术运算了。

最后,simpleInterest 是一个 Int,但我很确定 txtDisplay 需要一个 CharSequence,因此将 Int 转换回 String。

解决方案:

fun onSimpleInterest(view: View) {
    val str:String = txtDisplay.text.toString()
    val sp = str.split("[*+\-\/]".toRegex(), 3)
    val num1 = sp[0].toInt() // Possible Exceptions
    val num2 = sp[1].toInt()
    val num3 = sp[2].toInt()
    val simpleInterest = ((num1*num2)*num3)/100
    buttonSI.setOnClickListener {
        txtDisplay.text = simpleInterest.toString()
    }
}

注意:此处有许多实例可能引发您未捕获和处理的异常。

如果用户键入的元素少于 3 个,则拆分后的列表 return 的大小将小于 3。因此对其进行索引(sp[1],等等)可以 return IndexOutOfBoundsException.

同样在同一行,即使用户键入 3 个或更多元素,这些元素也可能不是整数。在这种情况下,尝试将它们转换为 Ints 可能 return NumberFormatException。

你应该处理这些可能性。