所以我正在打印我的变量 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()
}
}
}
你在这里创建了一个函数
recommendedCaloriesCalculator()
:
var recommendedCaloriesCalculator = {
recommendedCalories = ...
}
所以如果你没有明确调用
recommendedCaloriesCalculator()
,recommendedCalories = ...
将永远不会被执行,因此recommendedCalories
不会更新。
因此您可以在设置 TextView 之前调用
recommendedCaloriesCalculator()
。或者你可以简单地删除var recommendedCaloriesCalculator = { ... }
并留下recommendedCalories = ...
在那里:
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
// The simple solution is to remove recommendedCaloriesCalculator
// BTW, do you miss * for the following equations?
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()
}
}
}