首页 > 解决方案 > 在 kotlin 中循环

问题描述

我在 Kotlin 中制作了一个简单的计算器,但无法弄清楚为什么这个函数总是返回结果为零我认为我的 switch 语句中有错误但无法弄清楚在哪里?

我尝试替换 else 部分中的值,并意识到这是唯一正在执行的部分,并且所有其他案例都没有被执行

此外,如果我使用值 0 初始化 result ,这就是始终作为 result 返回的值。

class MainActivity : AppCompatActivity() {
lateinit  var myresult : TextView
lateinit  var val1 : EditText
lateinit var  btn : Button
lateinit var val2 : EditText
lateinit var operation : Spinner



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

     myresult = findViewById<TextView>(R.id.txtresult)
     val1 = findViewById<EditText>(R.id.valone)
     val2 = findViewById<EditText>(R.id.valtwo)
     var btn = findViewById<Button>(R.id.button)
     operation = findViewById<Spinner>(R.id.spinner)




    var opType = operation.selectedItem.toString()

    fun calculate() : Int {

        var value1 = Integer.parseInt(val1.text.toString())
        var value2 = val2.text.toString().toInt()
        var result : Int

        when (opType){

            "+" ->{result = value1 + value2
                    return result
                 }
            "-" ->{result = value1 - value2
                return result
            }
            "*" -> {result = value1 * value2
                return result
            }
            "/" -> {result = value1 / value2
                return result
            } else -> result = 0

        }

        return result
    }




    btn.setOnClickListener{

        println(calculate().toString())
        myresult.text = calculate().toString()


    }


}

}

标签: androidkotlin

解决方案


它可能返回零,因为这是提供未知 opType 时的默认值,并且您在 onCreate() 事件期间设置 opType,此时操作微调器的值尚未被选择。

顺便说一句,您应该尽可能避免使用 'var' 以避免线程安全问题并简化测试。我会亲自将您的计算函数重写为这样的东西,以便可以从按钮单击事件中调用它。

fun calculate(opType: String, value1: Int, value2: Int) : Int {
    return when (opType){
        "+" -> value1 + value2
        "-" -> value1 - value2
        "*" -> value1 * value2
        "/" -> value1 / value2
        else -> 0
    }
}

推荐阅读