我的简单kotlin计算器有错误
当我运行此代码时,我有问题。我想构建一个简单的计算器,因此我需要使用readline(),但是我在减法,乘法和除法操作中面临错误。这是代码,请帮助我。
fun main()
{
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nChoose Number: ")
var choosen = readLine()
print("Enter The First Number: ")
var num1 = readLine()
print("Enter The Second Number: ")
var num2 = readLine()
if (choosen?.toInt() == 1){
print("The Result Is: ${num1 + num2}")
} else if (choosen?.toInt() == 2){
print("The Result Is: ${num1 - num2}")
} else if (choosen?.toInt() == 3){
print("The Result Is: ${num1 * num2}")
} else if (choosen?.toInt() == 4){
print("The Result Is: ${num1 / num2}")
} else {
print("Wrong Input")
}
}
When I run this code, I have a problem. I want to build a simple calculator, so I need to use readLine() but I face error in subtraction, multiplication and division operations. This is the code, Please help me.
fun main()
{
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nChoose Number: ")
var choosen = readLine()
print("Enter The First Number: ")
var num1 = readLine()
print("Enter The Second Number: ")
var num2 = readLine()
if (choosen?.toInt() == 1){
print("The Result Is: ${num1 + num2}")
} else if (choosen?.toInt() == 2){
print("The Result Is: ${num1 - num2}")
} else if (choosen?.toInt() == 3){
print("The Result Is: ${num1 * num2}")
} else if (choosen?.toInt() == 4){
print("The Result Is: ${num1 / num2}")
} else {
print("Wrong Input")
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
- , *和/没有编译的原因是, num1 和 num2 是字符串。 +将起作用,但是它不会添加 num1 和 num2 ,它将加成两个值。
我建议使用 readln()而不是 readline(),因为您可以保证获得 string 。 readline()返回可选的字符串?。
可以用 tointornull()立即将输入转换为 int 。因此,如果输入的东西无法转换为 int ,我们将拥有 null for num1 和/或 num2 。
下一步是测试输入是否有效,因此如果子句。
只有输入有效时,将操作员应用于两个操作数才有意义。 语句比 语句更优雅时。
The reason that -, *, and / are not compiling is, that num1 and num2 are strings. + will work, but it will not add num1 and num2, it will concatenate the two values.
I would suggest to use readln() instead of readLine(), because you are guaranteed to get a String. readLine() returns an optional String?.
The input can immediately be converted to Int with toIntOrNull(). So if something is entered that can not be converted to an Int we will have null for num1 and/or num2.
The next step is to test if the input is valid, hence the if clause.
Only if the input is valid, it makes sense to apply the operator to the two operands. And the when statement is more elegant than multiple if else if statements.