我写了一个代表Polynom的类。 coefficients
保存系数。 unknown
拥有代表未知的char
。
coefficients
包含[2,2,3]:"2x^2 + 2x + 3"
现实:"122.0^2 + 2.0x + 3.0x"
代码:
public class Polynom implements Comparable<Polynom> {
private ArrayList<Number> coefficients;
private int degree = 0;
private char unknown = 'x';
private String name = "P(x)";
public Polynom() {
this("P(x)", 'x', null);
}
/**
* Accepts Format: A1x^n + A2x^n-1 + ... + A(n-1)^1 + An
* @param coefficients - Number array of coefficients (varargs)
*/
@SafeVarargs
public Polynom(Number... coefficients) {
this("P(x)", 'x', Arrays.asList(coefficients));
}
public Polynom(String name, char unknown, List<Number> coefficients) {
this.name = name;
if (coefficients != null)
this.coefficients = new ArrayList<>(coefficients);
else
this.coefficients = new ArrayList<>();
this.unknown = unknown;
this.degree = this.coefficients.size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(name + '=');
int cdeg = degree - 1;
for (Number a : coefficients) {
double absvalue = Math.abs(a.doubleValue());
String sign = (a.doubleValue() > 0 ? " + " : " - ");
if (absvalue > 1)
if (cdeg != degree - 1)
sb.append(sign + absvalue + unknown
+ (cdeg > 1 ? "^" + cdeg : ""));
else
sb.append(absvalue + unknown + (cdeg > 1 ? "^" + cdeg : ""));
else if (absvalue == 1)
if (cdeg != degree - 1)
sb.append(sign + unknown + (cdeg > 1 ? "^" + cdeg : ""));
else
sb.append(unknown + (cdeg > 1 ? "^" + cdeg : ""));
else
sb.append(sign + absvalue);
cdeg--;
}
return sb.toString();
}
@Override
public int compareTo(Polynom o) {...}
@Override
public boolean equals(Object o) {...}
}
public static void main(String[] args) {
Polynom p1,p2;
p1 = new Polynom(1,-2,3);
p2 = new Polynom(2,2,3);
System.out.println(p1+"\n"+p2);
}
答案 0 :(得分:1)
您的问题是,您尝试将char
连接到number
,这会导致添加而不是连接,因为不涉及String
。
当您将2+unknown
追加到StringBuilder
时,系统会2+'x'
追加122
,因为120
是字符&的数字值#39; X&#39;。)
将您的未知从char
更改为String
。
String unknown = "x";
这就是你需要改变的全部。