TheBulgarianWolf

Kotlin When

Mar 13th, 2021
815
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.36 KB | None | 0 0
  1. fun main(args: Array<String>) {
  2.     val a = 12
  3.     val b = 5
  4.  
  5.     println("Enter operator-either +,-,*, or /")
  6.     val operator = readLine()
  7.  
  8.     val result = when(operator){
  9.         "+" -> a + b
  10.         "-" -> a - b
  11.         "*" -> a * b
  12.         "/" -> a / b
  13.         else -> "$operator is invalid operator"
  14.     }
  15.  
  16.     println("The result is: $result")
  17.  
  18.     //the next one is more detailed one
  19.     val g = 15
  20.     val k = 9
  21.  
  22.     println("Enter operator-either +,-,*, or /")
  23.     val operator2 = readLine()
  24.  
  25.     when(operator2){
  26.         "+" -> println("$g + $k = ${g+k}")
  27.         "-" -> println("$g - $k = ${g-k}")
  28.         "*" -> println("$g * $k = ${g*k}")
  29.         "/" -> println("$g / $k = ${g/k}")
  30.         else -> "$operator2 is invalid operator"
  31.     }
  32.    
  33.     //few possibilities
  34.     val n = -1
  35.     when(n){
  36.         1,2,3 -> println("n is positive number less than 4")
  37.         0 -> println("n is zero")
  38.         -1,-2 -> println("n is a negative number greater than -3")
  39.     }
  40.    
  41.     //check value in range
  42.     val t = 100
  43.     when(a){
  44.         in 1..10 -> println("A positive number less than 11")
  45.         in 10..100 -> println("A positive number between 10 and 100(inclusive)")
  46.     }
  47.    
  48.     //value type check
  49.     print("Enter your string here: ")
  50.     val x = readLine()
  51.     when(x){
  52.         is String -> println(x.length + 1)
  53.     }
  54. }
Add Comment
Please, Sign In to add comment