-7

I am trying to represent an equation in this format: "a = bx + c"

  • If b is 0, it should return “a = c”.
  • If c is 0, then it should return “a = bx”
  • Also, when c is negative it should not return something like "5 = 8x + -7"
  • And when b=1, it should not show the coefficient of x.

Can you help me?

Emre
  • 933
  • 15
  • 27
  • Welcome to Stack Overflow! Please take the [tour], have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) – T.J. Crowder Oct 08 '16 at 09:46
  • Seems like each of those conditions that you've listed will end up as some kind of `if` statement in your code. You've already done the hard part - working out what all the various cases should be. Now have a go at writing some code. – Dawood ibn Kareem Oct 08 '16 at 09:47
  • http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Ario Oct 08 '16 at 09:48

1 Answers1

0

Just construct the string step by step in a StringBuilder:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder(a).append(" = ");

    if (b > 1 || b < -1) {
        sb.append(b);
    } else if (b == -1) {
        sb.append('-');
    }

    if (b != 0) {
        sb.append('x ');

        if (c > 0) {
            sb.append('+');
        } else if (c < 0) {
            sb.append('-');
        }

        sb.append(' ');
    }

    sb.append(Math.abs(c));

    return sb.toString();
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • `return` statement is missing. –  Oct 08 '16 at 10:04
  • @saka1029 huh, I went through all the trouble and forgot the punchline. Thanks for noticing! Edited and fixed. – Mureinik Oct 08 '16 at 10:07
  • Is `b` necessarily an integer? I was thinking of these variables as floating point, and I notice that you've made values of `b` between -1 and 1 disappear into thin air. – Dawood ibn Kareem Oct 08 '16 at 17:53