I have got error in my simple kotlin calculator - kotlin

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")
}
}

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.
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\nChoose Number: ")
val chosen = readln()
print("Enter The First Number: ")
val num1 = readln().toIntOrNull()
print("Enter The Second Number: ")
val num2 = readln().toIntOrNull()
if (chosen !in listOf("1", "2", "3", "4") || num1 == null || num2 == null) {
print("Invalid input")
} else {
val result = when (chosen) {
"1" -> num1 + num2
"2" -> num1 - num2
"3" -> num1 * num2
"4" -> num1 / num2
else -> null // will never happen, see 'if' clause
}
print("The result is: $result")
}

Related

Checking if user entered data type int with if else statement Kotlin

EDIT: ANSWER TO THIS IS BELOW
Really new to kotlin, wanting to check if user entered an Integer, using if else statement. Need to add a do while loop to it later.
Expecting Error Message: Incorrect
When I hover over (input != pin) it displays
Condition 'input != pin' is always true.
Here's my code
fun main() {
println("Create PIN: ")
val pin = readln().toInt()
println("Enter PIN: ")
val input = readln().toInt()
if (input == pin){
println ("Correct")
}
else if (input != pin) {
println("Incorrect")
}
}
Because if input == pin is false so input != pin is always true, that's why you don't need the second else if you can just replace it with if:
fun main() {
println("Create PIN: ")
val pin = readln().toInt()
println("Enter PIN: ")
val input = readln().toInt()
if (input == pin){
println ("Correct")
}
else {
println("Incorrect")
}
}
But now if the user enters something that can't be converted to int ( some characters for example "hello"... ) .toInt() is going to throw a NumberFormatException and your code is not going to work so to fix that problem and handle the case when a user enters something other that Int, you can use .toIntOrNull() instead of .toInt().
.toIntOrNull(): Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.
So if pin or input is null, that mean that the user enters something that can't be converted to Int.
fun main() {
println("Create PIN: ")
val pin = readln().toIntOrNull()
println("Enter PIN: ")
val input = readln().toIntOrNull()
if (input == null || pin == null) {
println("PIN is not valid")
}
else if (input == pin){
println ("Correct")
}
else {
println("Incorrect")
}
}

Kotlin when change value

can i use when in Kotlin to change the value of an existing variable?
i understand this one:
val num = 1
val result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
should be "positive"
but i want this( psuedo )....
val num = 1
var result = "init string"
//bunch of code here
// later....
result = when{
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
it writes positive, but it says "Variable "result" initializer is redundant.
What im missing here?
Thx
The line
var result = "init string"
is redundant because you leave no possibility of that value not getting overridden in the when statement. "init string" cannot be printed at the end of the code, the variable will always have one of the three possible values defined in the when.
But you can directly initialize result with the when statement:
fun main() {
var num = 1
// directly assign the result of the when statment to the variable
var result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
}
This prints
positive
thank you for the answer.
But i can say....
fun main() {
var num = 1
// directly assign the result of the when statment to the variable
var result = when {
num > 0 -> "positive"
num < 0 -> "negative"
else -> "zero"
}
println(result)
// and then later reassign....
num = 2
result = when{
num == 2 -> "two"
else -> "not two"
{
println(result)
// prints two
}
So i cant reassign an existing string with a when statement, that is not initialized with an another when statement?
I hope this is readable. :)
Thank you.
dagogi

Kotlin - Unexpected tokens (use ';' to separate expressions on the same line) with ternary operator in lambda function

I got an error Unexpected tokens error on the lambda function when I try to run this code:
fun main() {
val oddOrEven = { number: Int -> (number % 2 == 0) ? "Even" : "Odd" }
print(oddOrEven(2))
}
There's no ternary operator in Kotlin. See the discussion here.
if in Kotlin is an expression (so it can return a value) and you can do something like this:
fun main() {
val oddOrEven = { number: Int -> if(number % 2 == 0) "Even" else "Odd" }
println(oddOrEven(2))
}
There is a special operator:
val x = if (y == null) -1 else x
The above can be shortened to:
val x ?: -1
This is called the Elvis Operator - if the value is null it returns the other value (-1 in this case)

Kotlin when expression issue for calculating (calculator) new to kotlin

//Error due to receive type mismatch but it the logic seems ok to me
fun main(args : Array<String>){
println("Enter a number")
var a = readLine()
println("Choose your operator")
val operator = readLine()
println("Enter a second number")
var b = readLine()
var result = when (operator) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> "invalid operator or number"
}
println("Results = $result")
}
In this case, a and b are type String. This means they don't have the -, /, or * operators. I'm going to guess you probably want them to be Ints so you can perform mathematical operations with them.
To do that, we can convert them to Int after we read them:
println("Enter a number")
var a: Int = readLine()?.toInt() ?: throw IllegalArgumentException("Must be an Int")
println("Enter a second number")
var b: Int = readLine().toInt() ?: throw IllegalArgumentException("Must be an Int")
I've explicitly typed a and b as Ints in this example, so we can see how it works. What this new code says is "read a line of input and try to turn it into an Int, if that doesn't work, throw an IllegalArgumentException. You could rewrite this to keep trying, but we're going to leave that bit up to you.
One more thing I would fix is that result is type Any because it can be either an Int (if we know about the operator) or a String (if we don't). I would change it so the invalid operator also throws an exception.
And again, I've typed this explicitly as Int:
var result: Int = when (operator) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> throw IllegalArgumentException("Invalid operator")
}
The problem is that you have input value as string, you have to convert them to int.
Here my code:
fun main(){
println("Enter a number")
val a = readLine()?.toInt()
println("Choose your operator")
val operator = readLine()
println("Enter a second number")
val b = readLine()?.toInt()
if( a != null && b != null) {
val result = when (operator) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> "invalid operator or number"
}
println("Results = $result")
}
}

Loop String from Console and sum odd numbers

fun main(args: Array<String>) {
println("Number: ")
val num = readLine()!!.toInt()
var sum = 0
for (digit in num) {
if (digit % 2 != 0) {
sum += digit
}
}
println("$sum")
}
I need this loop to go through every digit in the number and sums all the digits that are odd.
It gives me an error on num "For-loop range must have an 'iterator()' method"
You cannot iterate over an Int like num:
val num = readLine()!!.toInt()
You can fix it without a loop and by using standard functions map, filter and sum:
val sum = readLine()!!.toCharArray()
.map { it.toString().toInt() }
.filter { it % 2 != 0 }
.sum()
The filter-condition for even numbers would be it % 2 == 0
EDIT
For your homework, do this:
val num = readLine()!!.toCharArray()
var sum = 0
for (a in num) {
val intVal = a.toString().toInt()
if (intVal % 2 != 0) {
sum += intVal
}
}