[英]A piece of code is telling me "The Expression is unused"
我对应用程序开发很陌生。 我卡在一段代码上,告诉我“表达式未使用”。
该应用程序本身是在 Kotlin 中编写的,它是一个转换应用程序。 我很确定我算对了,因为 1 英尺等于 30.48 厘米,这是正确的。 但是,每当我(在应用程序中)写一个大于 1 英尺的数字时,它仍然总是 30.48 厘米。 例如,如果我在应用程序中输入 5foot 9,答案仍然是 30.48cm。 这是两个代码块,我很确定其中一个是罪魁祸首。
第一个。
'calculateHeight' 是给我“The Expression is unused”的那一行
private fun calculateButton() {
val feetString: String = binding.editTextFeet.text.toString()
val inchesString: String = binding.editTextInches.text.toString()
val calculateHeight = calculateHeight()
if (feetString.isEmpty()) {
Toast.makeText(context, "Please select a foot value", Toast.LENGTH_SHORT).show()
} else {
calculateHeight
displayText()
}
if (inchesString.isEmpty()) {
Toast.makeText(context, "Please select a inch value", Toast.LENGTH_SHORT).show()
} else {
calculateHeight
displayText()
}
}
第二个。
private fun calculateHeight(): Double {
val feetHint = binding.editTextFeet.toString()
val inchesHint = binding.editTextInches.toString()
var feet = 1
try {
feet = feetHint.toInt()
} catch (e: NumberFormatException) {
e.printStackTrace()
}
var inches = 0f
try {
inches = inchesHint.toInt().toFloat()
} catch (e: NumberFormatException) {
e.printStackTrace()
}
val totalFeet = feet * 12
val totalInches = inches + 1f
val heightInCentimeters = 2.54
return ((totalFeet * totalInches) * heightInCentimeters)
}
}
这是显示文本():
private fun displayText() {
val dec = DecimalFormat(".##")
val resultString: String = dec.format(calculateHeight())
binding.textViewCm.text = "$resultString - Centimeters"
}
val calculateHeight = calculateHeight()
此行调用calculateHeight()
function。该 function 会及时读取您字段的内容并对其内容执行计算。 然后将calculateHeight()
function 的结果存储在变量中,该变量本身容易混淆地命名为calculateHeight
。
然后,您不会对calculateHeight
做任何有意义的事情。 您在随后不执行任何操作的语句中引用该变量两次:
calculateHeight
这些行会给你“表达式未使用”,因为表达式 ( calculateHeight
) 未使用。 你没有用它做任何事情。
它仍然总是30.48cm
您不知道 state 您在哪里以及如何看到任何结果。 如果我不得不猜测,给定 function 的名称, displayText()
应该是类似的东西。您的问题不包括displayText()
的来源,所以我们不得不猜测。
但是,尚不清楚displayText()
在哪里显示任何内容。 您没有将任何参数传递给displayText()
。 也许你应该有displayText(calculateHeight)
,并让你的displayText()
function 接受那个参数并用它做一些事情。 或者,也许displayText()
应该直接调用calculateHeight()
,您可以从calculateButton()
function 中删除所有calculateHeight()
/ calculateHeight
内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.