Print Number with its Sign in Java
Sometimes we need to print the numbers with its sign irrespective of number is positive (+) or negative(-).
X = 5, print = +5 Y = -8, print = -8
Say we need to print a equation : 2x – 3y – 6 = 0 and if you will use
System.out.println(“Equation: “+ a + “x + ” +b+ “y + ” + c );
The output will be 2x + -3y + -6 which is wrong.
Use System.out.format and use %+d to print the sign of the number
Use System.out.format(“Equation: %+dx %+dy %+d = 0”, a, b, c );Output: +2x -3y -6 = 0
Wrong Equation: 2x + -3y + -6 Correct Equation: +2x -3y -6 = 0
Top Companies Interview Questions..-
If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.