5

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

Selena Gomez
  • 69
  • 1
  • 7

3 Answers3

6

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.

devnull
  • 118,548
  • 33
  • 236
  • 227
3

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
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

you need to add + in your string for positive numbers. you can do something like following. So better take a string and add your variables there. While adding consider following three things

  1. if the variable is 0 dont add that part at all.
  2. if the variable is positive add a '+' then the variable
  3. if the variable is negative just add the variable
stinepike
  • 54,068
  • 14
  • 92
  • 112