In this article, we will understand how to check whether a number is positive or negative. This is accomplished by checking if the given number is greater or less then 0. Show Below is a demonstration of the same − Input Suppose our input is − Enter the number: -3 Output The desired output would be − The number -30 is a negative number AlgorithmStep 1 - START Step 2 - Declare an integer values namely my_input. Step 3 - Read the required values from the user/ define the values Step 4 - Using an if-else condition, check my_input > 0 value. Step 5 - If the result is true, then it’s a positive number, else it’s a negative number. Step 6 - Display the result Step 7 - Stop Example 1Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool import java.util.Scanner; public class PositiveNegative { public static void main(String[] args) { int my_input; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the number : "); my_input = my_scanner.nextInt(); if(my_input > 0) System.out.println("The number " +my_input + " is a positive number"); else System.out.println("The number " +my_input + " is a negative number"); } } OutputRequired packages have been imported A reader object has been defined Enter the number : -30 The number -30 is a negative number Example 2Here, the integer has been previously defined, and its value is accessed and displayed on the console. public class PositiveNegative { public static void main(String[] args) { int my_input; my_input = -30; System.out.println("The number is defined as " +my_input); if(my_input > 0) System.out.println("The number " +my_input + " is a positive number"); else System.out.println("The number " +my_input + " is a negative number"); } } OutputThe number is defined as -30 The number -30 is a negative number
Updated on 22-Feb-2022 10:52:36
Read a number from the user using the Scanner class's method. check whether the given number is greater, lesser or, equal to 0. If it is greater given number is positive if the lesser given number is negative. the else given number is neither positive or negative. Exampleimport java.util.Scanner; public class PositiveOrNegative { public static void main(String args[]){ int num; System.out.println("Enter a number ::"); Scanner sc = new Scanner(System.in); num = sc.nextInt(); if (num > 0){ System.out.println("Given number is a positive integer"); } else if(num < 0){ System.out.println("Given number is a negative integer"); } else { System.out.println("Given number is neither positive nor negative integer"); } } } Output 1Enter a number :: 55 Given number is a positive integer Output 2Enter a number :: -88 Given number is a negative integer
Updated on 13-Mar-2020 07:03:14
|