germainelol
germainelol

Reputation: 3331

Java - toString method for polynomial Terms

I have created a polynomial class without using Polynomial, I am using my own Term(coefficient, exponent) to create the polynomial expression.

I have some conditions which are as follows:

coefficient = 0 -> Term(0,2) -> 0x^2 -> "0"
coefficient = 1 -> Term(1,2) -> 1x^2 -> "x^2"
coefficient = -1 -> Term(-1,2) -> -1x^2 -> "-x^2"
exponent = 1 = -> Term(5,1) -> 5x^1 -> "5x"
exponent = 0 = -> Term(5,0) -> 5x^0 -> "5"

But implementing all of these to function in and around each other is causing me a massive headache, for example if I have Term(-1,1) I would like "-x" to appear, and "x" for Term(1,1). Can anyone help with thinking of some sort of logic to group all of these "rules" together for a toString method?

Upvotes: 3

Views: 4260

Answers (5)

Yogendra Singh
Yogendra Singh

Reputation: 34367

I think, you don't expo will not be negative. Try something as below:

@Override
public String toString() {
    if(coef ==0){
        return "0";
    }else if(expo ==0){
        return ""+coef;
    }else{
        String pref = coef==1? "": coef==-1?"-":""+coef; 
        String suff = expo>1? "^"+expo:""; 
        return pref+"x"+suff;
    }
}

EDIT: To use StringBuilder, change last statement as below(I don't see much benefit though)

   return new StringBuilder(pref).append("x").append(suff).toString();

Upvotes: 1

Grambot
Grambot

Reputation: 4524

Hmmm there really isn't much you can do to make it easier. you essentially have the following cases:

Coefficient = 0 --> Display 0 (exponent irrelevant)
Coefficient = +/- 1 --> Display - if -1 (special case of (-1,0)), nothing otherwise
Other Coefficients --> Display as stored

Exponent = 0 --> display nothing
Otherwise, display x^exponent...

So.....

public String toString() {
  String term = "";

  if (coefficient == 0) {
    return "0";
  } elseif (coefficient == -1) {
    if (exponent == 0) {
      return "-1";
    } else {
      term += "-";
    }
  } elseif (coefficient != 1) {
    term += String.valueOf(coefficient);
  } else {
    if (exponent == 0) {
      return "1";
    }
  }

  if (exponent != 0) {
    if (exponent == 1) {
      term += "x";
    } else {
      term += "x^" + String.valueOf(exponent);
    }
  }

  return term;
}

I think that covers it? I didn't put it through UnitTest to really be sure.

Upvotes: 0

ShyJ
ShyJ

Reputation: 4640

This is as close as I got to to make it clear

public class Term { 
    private final int coefficient;
    private final int exponent;

    public Term (final int coefficient,final int exponent) {
        this.coefficient = coefficient;
        this.exponent = exponent;           
    }

    @Override
    public String toString() {
        final String sign = getSign (coefficient);
        final String number = getNumber (coefficient);
        final String exponentStr = getExponentStr (coefficient, exponent);

        return String.format ("%s%s%s",sign, number, exponentStr);
    }

    private String getExponentStr(final int coefficient, final int exponent) {
        if (coefficient == 0 || exponent == 0) {
            return "";
        }
        if (exponent == 1) {
            return "x";
        }
        return "x^" + exponent;
    }

    private String getNumber(final int value) {
        final int absValue = Math.abs(value);

        return absValue == 1 ? "" : Integer.toString (absValue);
    }

    private String getSign(final int value) {
        return value < 0 ? "-" : "";
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Term (0, 2));
        System.out.println(new Term (1, 2));
        System.out.println(new Term (-1, 2));
        System.out.println(new Term (5, 1));
        System.out.println(new Term (5, 0));
    }
}

And a fiddle for it.

Upvotes: 1

Jacob Schoen
Jacob Schoen

Reputation: 14212

The order is important here. If you think it through, you will see that coefficient = 0 should go first, since when it is zero nothing else matters. Next are the special cases for when the exponent equals 1 or 0. Then you have when the coefficient is -1. All that is left then is the default case of either a negative coefficient other than -1 or a positive coefficient. So the if statement should look like:

public String toString() {
    if(coefficient == 0){
      return "0";
    } else if ( coefficient == 1 && exponent != 0){
        return "x^"+exponent; 
    } else if ( exponent == 1){
      return coefficient+"x"; 
    } else if ( exponent == 0){
      return ""+coefficient; 
    } else if ( coefficient == -1){
      return "-x^"+exponent; 
    } else {
      return coefficient+"x^"+exponent; 
    }
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

You can combine the first special case with the last one. You can also combine the second and third cases by looking at the abs value of the coefficient.

// If the coefficient is zero or the exponent is zero,
// the result is simply the coefficient:
if (c == 0 || e == 0) {
    return ""+c;
}
StringBuilder res = new StringBuilder();
// Do not print the number for the coefficient of +/- 1
if (Math.abs(c) == 1) {
    // For +1 do not print the sign either
    if (c == -1) {
        res.append("-");
    }
} else {
    res.append(c);
}
res.append("x");
// For exponent of 1, do not print ^1
if (e != 1) {
    res.append("^");
    res.append(e);
}
return res.toString();

Upvotes: 1

Related Questions