有人可以解释这个奇怪的toString行为吗?

时间:2014-12-31 17:34:56

标签: java tostring behavior

我写了一个代表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);
}

1 个答案:

答案 0 :(得分:1)

您的问题是,您尝试将char连接到number,这会导致添加而不是连接,因为不涉及String

当您将2+unknown追加到StringBuilder时,系统会2+'x'追加122,因为120是字符&的数字值#39; X&#39;。)

将您的未知从char更改为String

String unknown = "x";

这就是你需要改变的全部。