Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printing symbol for positive number

Tags:

java

I have a Java program that does a bunch of calculations from some user inputs and at the end it has to print the equation of the plane. Format of the equation of the plane is 6x-2y+3z-4=0.

To get the values 6, -2, 3, & -4 is from a bunch of calculations. So i was thinking to print out the equation is to

System.out.println("Equation is: " + aa + "x" + bb +
"y" + cc + "z" + gg + "=0");

Where aa, bb, cc , gg corresponds to the 4 integers above. But the output is

Equation is: 6x-2y3z-4=0

It seems to print the minus signs in there for the negative numbers but how can i have it print out a plus sign if the number is positive? Like in between -2y3z should be 6x-2y+3z-4=0

like image 463
Selena Gomez Avatar asked Apr 08 '14 05:04

Selena Gomez


People also ask

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What does %d do in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.

What is %N in Java printf?

By using %n in your format string, you tell Java to use the value returned by System. getProperty("line. separator") , which is the line separator for the current system.


2 Answers

You could use System.format():

System.out.format("Equation is: %dx %+dy %+dz %+d = 0\n", aa, bb, cc, gg);
                                     ^    ^    ^

Specifying the + flag would include the sign whether positive or negative.

You can find more information about formatting numeric output here.

like image 155
devnull Avatar answered Dec 08 '22 18:12

devnull


You can try using printf() to display a formatted output:

int aa = 6;
int bb = -2;
int cc = 3;
int gg = -4;

System.out.printf("Equation is: %dx%+dy%+dz%+d=0", aa, bb, cc, gg);

Here you are ussing the format modifier %+d, to specify that the sign must be displayed, even if the number is positive.

Output:

Equation is: 6x-2y+3z-4=0
like image 21
Christian Tapia Avatar answered Dec 08 '22 17:12

Christian Tapia