如何在变量中使用等式与if语句?推荐卡路里计算结果异常排查
问题
打印recommendedCalories变量时,传入默认值0会输出0,但使用前一页面传递的变量值时,本该得到不同结果却没达到预期,等式计算为何没得到想要的结果?
原代码
package com.example.optilife import... class WelcomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_welcome) val userAge = intent.getIntExtra("EXTRA_AGE", 0) val userHeight = intent.getIntExtra("EXTRA_HEIGHT", 0) val userWeight = intent.getIntExtra("EXTRA_WEIGHT", 0) val userGender = intent.getStringExtra("EXTRA_GENDER") val userActivityLevel = intent.getStringExtra("EXTRA_ACTIVITYLEVEL") var userWeightGoal = intent.getStringExtra("EXTRA_WEIGHTGOAL") var userWeightGoalCalories = { userWeightGoal = if (userWeightGoal == "Weight loss") { "300" } else if (userWeightGoal == "Maintain weight") { "0" } else { "-300" } } var recommendedCalories = 0 var recommendedCaloriesCalculator = { recommendedCalories = if (userGender == "Male") { (66 + 13.7userWeight + 5userHeight - 6.8userAge - userWeightGoal.toString().toInt()).toString().toInt() } else { (655 + 9.6userWeight + 1.8userHeight - 4.7userAge - userWeightGoal.toString().toInt()).toString().toInt() } } findViewById<TextView>(R.id.tv_Test).apply { text = recommendedCalories.toString() } } }
问题原因
- 你定义了
userWeightGoalCalories和recommendedCaloriesCalculator两个lambda表达式,但完全没调用它们,里面的转换和计算逻辑根本没执行,recommendedCalories一直是初始值0。 - 代码存在语法错误:Kotlin中乘法必须写
*运算符,13.7userWeight、5userHeight这种写法会直接编译失败,根本跑不到计算步骤。 userWeightGoal本身就是字符串类型,不需要额外调用toString(),冗余操作无意义。
修正后的代码
package com.example.optilife import... class WelcomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_welcome) val userAge = intent.getIntExtra("EXTRA_AGE", 0) val userHeight = intent.getIntExtra("EXTRA_HEIGHT", 0) val userWeight = intent.getIntExtra("EXTRA_WEIGHT", 0) val userGender = intent.getStringExtra("EXTRA_GENDER") val userActivityLevel = intent.getStringExtra("EXTRA_ACTIVITYLEVEL") var userWeightGoal = intent.getStringExtra("EXTRA_WEIGHTGOAL") // 直接执行体重目标转换逻辑,无需用lambda包裹 userWeightGoal = when(userWeightGoal) { "Weight loss" -> "300" "Maintain weight" -> "0" else -> "-300" } // 直接计算推荐热量,避免冗余的变量赋值 val recommendedCalories = if (userGender == "Male") { (66 + 13.7 * userWeight + 5 * userHeight - 6.8 * userAge - userWeightGoal.toInt()).toInt() } else { (655 + 9.6 * userWeight + 1.8 * userHeight - 4.7 * userAge - userWeightGoal.toInt()).toInt() } findViewById<TextView>(R.id.tv_Test).apply { text = recommendedCalories.toString() } } }
修正说明
- 移除了未调用的lambda表达式,直接执行转换和计算逻辑,确保代码能运行到关键计算步骤。
- 补充了缺失的乘法运算符
*,修复编译错误。 - 用
when语句替代嵌套if-else,代码更简洁易读。 - 删除了冗余的
toString()调用,优化代码逻辑。
内容的提问来源于stack exchange,提问作者JenairoB
相关产品推荐
相关产品推荐

