373
In this example we show how to check if a number is positive, negative or zero in Java
Example
We take user input then use an if – else statement to check whether the number is less than, greater than or equal to 0.
import java.util.Scanner; public class JavaApplication1 { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a number: "); int number = reader.nextInt(); // true if number is less than 0 if (number < 0.0) System.out.println(number + " is a negative number."); // true if number is greater than 0 else if ( number > 0.0) System.out.println(number + " is a positive number."); // if both test expression is evaluated to false else System.out.println(number + " is 0."); } }
A few runs of this
run: Enter a number: -1 -1 is a negative number. run: Enter a number: 2 2 is a positive number. run: Enter a number: 0 0 is 0.