android - 在 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()
}
}
}
解决方案
它可能返回零,因为这是提供未知 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
}
}
推荐阅读
- json - 尝试使用 REST.Json 将 json 转换为对象时,EConvert 异常无效日期时间
- powershell - 从 csv 文件中删除某些重复值
- c++ - Trying to find all prime numbers in a list
- python - 如何过滤数据框并立即制作一个子集 pandas
- java - `visitMethodCall` 没有在 lint 中被调用
- r - 在数据框中添加随机缺失和随机噪声
- wordpress - 如何在分类中显示 ACF 图像字段
- powershell - 使用 powerShell 问题在 AD 中允许/Denny logOnHours
- python - 使用日期时间和类别重新组合 pandas 数据框
- visual-studio-code - vs代码扩展命令运行详解