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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With