我正在尝试将结果打印为双精度并收到以下错误:-
线程“ main”中的异常java.lang.NumberFormatException:对于输入字符串:“ kotlin.Unit”
我该如何解决?
def esm(data, ratio):
X = series[data].values
size = int(len(X) * ratio)
for data in ["col1", "col2", "col3", "col4"]:
for ratio in [0.6, 0.7, 0.8, 0.9]:
esm(data, ratio)
# do something
答案 0 :(得分:2)
问题出在这行
calculateWeight(150.0).toString().toDouble()
在calculateWeight函数中,因为没有返回类型,它将解析为默认值kotlin.Unit
,您尝试使用toDouble()
将其转换为 Double ,将其删除即可使用完美。而且异常在方法执行后发生,因为它发生在函数返回的值上。希望这会有所帮助
答案 1 :(得分:1)
删除.toString().toDouble()
部分,然后以这种方式实现以解决小数格式问题:
fun calculateWeight(bodyWeight: Double) {
val mercury = bodyWeight * 0.38
val venus = bodyWeight * 0.91
val earth = bodyWeight * 1.00
val mars = bodyWeight * 0.38
val jupiter = bodyWeight * 2.34
val saturn = bodyWeight * 1.06
val uranus = bodyWeight * 0.92
val neptune = bodyWeight * 1.19
val pluto = bodyWeight * 0.06
println("My body weight is %.2f pounds and on the different planets it equals:\n" +
"Mercury: %.2f, \nVenus: %.2f, \nEarth: %.2f, " +
"\nMars: %.2f, \nJupiter: %.2f, \nSaturn: %.2f, \nUranus: %.2f," +
"\nNeptune: %.2f, \nPluto: %.2f".format(
bodyWeight, mercury, venus, earth, mars,
jupiter, saturn, uranus, neptune, pluto))
}
更好的是,这是一种更惯用的方式。
enum class Planet(val relativeGravity: Double) {
Mercury(0.38),
Venus(0.91),
Earth(1.00),
Mars(0.38),
Jupiter(2.34),
Saturn(1.06),
Uranus(0.92),
Neptune(1.19),
Pluto(0.06);
fun convert(weight: Double): Double {
return weight * relativeGravity
}
}
fun calculateWeight(bodyWeight: Double, unit: String = "pounds") {
val prefix = "My body weight is $bodyWeight $unit and on the different planets it equals:\n"
println(Planet.values().joinToString(prefix = prefix, separator = ",\n") { planet ->
"%s: %.2f".format(planet.name, planet.convert(bodyWeight))
})
}