In this post, we will go through Kotlin Program to Check If Number is Positive or Negative.
A given number is –
- 1. positive if it is greater than 0.
- 2. negative if it is less than 0.
- 3. zero if it is equal to 0.
1. Check Whether number if positive or negative.
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter Number:") val numb = read.nextInt() val msg = if(numb > 0) { "Given number is positive." } else if(numb == 0){ "Given number is zero." } else { "Given number is negative." } println(msg) }
When you run the program, output will be
Enter Number: 230 Given number is positive.
Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.
read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable year
As we have already discussed necessary conditions to check if number is positive/negative/zero, we did so using if-else
conditions.
Finally, we print result (i.e. msg value) value using println() method.
2. Check Positive/Negative Using When Block
In the previous example, we used if-else block. Now, we will use when block in kotlin to check if number is positive/negative.
import java.util.* fun main() { val read = Scanner(System.`in`) println("Enter Number:") val numb = read.nextInt() val msg = when { numb > 0 -> { "Given number is positive." } numb == 0 -> { "Given number is zero." } else -> { "Given number is negative." } } println(msg) }
When you run the program, output will be
Enter Number: 250 Given number is positive.
Here, we have created an object of Scanner. Scanner takes an argument which says where to take input from.
System.`in` means take input from standard input – Keyboard.
read.nextIn() means read anything entered by user before space or line break from standard input – Keyboard.
Input read by scanner is then stored in variable year
As we have already discussed necessary conditions to check if number is positive/negative/zero, we did so using when block
conditions in kotlin.
Finally, we print result (i.e. msg value) value using println() method.
Thus, we went through Kotlin Program to Check If Number is Positive or Negative.