Kotlin计算器小数处理异常:输入报错、结果自动取整问题
解决Kotlin计算器的小数运算与输入异常问题
问题根源
- 原代码通过
toInt()将输入转换为整数类型,导致输入小数时直接抛出NumberFormatException - 整数类型的除法运算会自动截断小数部分,无法保留运算结果的小数位
修复后的代码
fun main() { println("This is a calculator") // 读取并解析第一个数字,处理非数字输入 val no1 = try { println("enter your first number") readLine()?.toDouble() ?: throw IllegalArgumentException("Input cannot be empty") } catch (e: NumberFormatException) { println("Invalid number input. Please enter a valid number.") return } // 读取运算操作符 println("enter your operation (+, -, *, /)") val operation1 = readLine()?.trim() ?: "" // 读取并解析第二个数字,处理非数字输入 val no2 = try { println("enter your second number") readLine()?.toDouble() ?: throw IllegalArgumentException("Input cannot be empty") } catch (e: NumberFormatException) { println("Invalid number input. Please enter a valid number.") return } // 执行运算并处理异常情况 when (operation1) { "*" -> println("Result: ${no1 * no2}") "+" -> println("Result: ${no1 + no2}") "-" -> println("Result: ${no1 - no2}") "/" -> { if (no2 == 0.0) { println("Error: Cannot divide by zero") } else { println("Result: ${no1 / no2}") } } else -> println("Please enter a valid operation: +, -, *, /") } }
关键改动说明
- 支持小数运算:将输入转换为
Double类型,替代原有的Int类型,既支持整数输入也支持小数输入,运算结果保留小数位 - 输入异常处理:用
try-catch捕获NumberFormatException,当用户输入非数字内容时给出提示并终止程序,避免崩溃 - 除零校验:针对除法操作单独处理除零情况,给出明确的错误提示
- 优化逻辑结构:用
when表达式替代嵌套if-else,代码更简洁易读;统一使用println输出结果,避免原代码中result变量无实际意义的问题
内容的提问来源于stack exchange,提问作者user17569387
相关产品推荐
相关产品推荐

