Hello! Tell me by code, is the code correctly formed, or am I not correctly using the math function Math.signum(a) ? Here is the task:

  • The variable n contains some real number.
  • Calculate and display the value of the signum function from this number (-1 if the number is negative; 0 if it is zero; 1 if it is positive).

 public class Signum { public static void main(String args[]){ final double a = 3; final double b = 0; final double c = -3; double signum_a = Math.signum(a); double signum_b = Math.signum(b); double signum_c = Math.signum(c); System.out.println(signum_a); System.out.println(signum_b); System.out.println(signum_c); } } 
  • Is the result correct? - Nofate
  • The result is correct, but I would read the number n from the console. - Ilmirus
  • but do not tell me how to correctly read the number n from the console - turtles

2 answers 2

If this is a learning task, then most likely you yourself must calculate the signum.

 return n == 0 ? 0 : n < 0 ? -1 : 1 

PS: Input from the console is as follows:

 Scanner in = new Scanner(System.in); int n = in.nextInt(); 

    If you are told to do this training task in Java, then that's right. Why invent a bicycle yourself if there is a library in which it is already implemented. That's right.