Kotlin 错误:线程“中出现异常”;“主要”;java.lang.NumberFormatException:对于输入字符串:";科特林单位“;
我试图将结果打印为双精度打印,但收到以下错误:- 线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“kotlin.Unit” 我该如何解决这个问题Kotlin 错误:线程“中出现异常”;“主要”;java.lang.NumberFormatException:对于输入字符串:";科特林单位“;,kotlin,Kotlin,我试图将结果打印为双精度打印,但收到以下错误:- 线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“kotlin.Unit” 我该如何解决这个问题 calculateWeight(150.0).toString().toDouble() } fun calculateWeight(bodyWeight: Double) { val mercury = bodyWeight * 0.38 val venus = bodyWei
calculateWeight(150.0).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 $bodyWeight pounds and on the different planets it equals:\n" +
"Mercury: $mercury, \nVenus: $venus, \nEarth: $earth, " +
"\nMars: $mars, \nJupiter: $jupiter, \nSaturn: $saturn, \nUranus: $uranus," +
"\nNeptune: $neptune, \nPluto: $pluto")
问题在于这条线
calculateWeight(150.0).toString().toDouble()
在CalculateWight函数中,由于没有返回类型,它将解析为默认的kotlin.Unit
,您正试图使用toDouble()
将其转换为Double。方法执行后发生异常,因为它发生在函数返回的值上。希望这有助于删除.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))
})
}
谢谢我以前是这样的,重量是150,结果打印为双倍,但是,当我把重量改为115时,我得到了如下结果:我的体重是115.0磅,在不同的行星上它等于:水星:43.7,金星:104.65,地球:115.0,火星:43.7,木星:269.0999999997,土星:121.9,天王星:105.800000000001,海王星:136.85,冥王星:6。8999999999999995@SKdev浮点不能准确地存储十进制数。见例。一个解决方案可能是使用
BigDecimal
来代替。@gidds谢谢,我将查看链接。太棒了!成功了!我使用了第二种解决方案。非常感谢你。