Java Online Compiler
Example: Check Number Sign with signum() method in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Check Number Sign with signum() method import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object Scanner scanner = new Scanner(System.in); // Step 2: Prompt and read the number (using int for Integer.signum()) System.out.print("Enter an integer: "); int intNumber = scanner.nextInt(); // Step 3: Get the sign using Integer.signum() int intSign = Integer.signum(intNumber); // Step 4: Print the result based on the sign if (intSign == 1) { System.out.println(intNumber + " is a positive number (using Integer.signum())."); } else if (intSign == -1) { System.out.println(intNumber + " is a negative number (using Integer.signum())."); } else { System.out.println(intNumber + " is zero (using Integer.signum())."); } // Step 5: Prompt and read a double (for Math.signum()) System.out.print("Enter a floating-point number: "); double doubleNumber = scanner.nextDouble(); // Step 6: Get the sign using Math.signum() double doubleSign = Math.signum(doubleNumber); // Returns 1.0, -1.0, or 0.0 // Step 7: Print the result based on the sign if (doubleSign == 1.0) { System.out.println(doubleNumber + " is a positive number (using Math.signum())."); } else if (doubleSign == -1.0) { System.out.println(doubleNumber + " is a negative number (using Math.signum())."); } else { System.out.println(doubleNumber + " is zero (using Math.signum())."); } // Step 8: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS