Be the first user to complete this post

  • 0
Add to List
Beginner

348. 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

Output:

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