Print Number with its Sign in Java

Sometimes we need to print the numbers with its sign irrespective of number is positive (+) or negative(-).

Example:

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

Java Code:

Output:

Wrong Equation: 2x + -3y + -6
Correct Equation: +2x -3y -6 = 0

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: