我有一個單項式的結構,需要在合作效率和三個變量作爲單一number.My單項類指數看起來是這樣的:存儲鏈表在Java中添加兩個多項式
public class Monomial {
private Float coeff;
private Integer exp;
private Integer x,y,z;
public Monomial() {
this.coeff=null;
this.x=this.y=this.z=null;
this.exp=null;
}
public Monomial(Float coeff, Integer x, Integer y, Integer z) {
this.coeff = coeff;
this.x = x;
this.y = y;
this.z = z;
this.exp = (100*x)+(10*y)+z;
}
public Monomial(Integer exp) {
this.exp = exp;
this.x=(exp-(exp%100))/100;
this.z = exp%10;
this.y = ((exp-z)/10)%10;
}
public Monomial(Float coeff, Integer exp) {
this.coeff = coeff;
this.exp = exp;
this.x=(exp-(exp%100))/100;
this.z = exp%10;
this.y = ((exp-z)/10)%10;
}
}
我的多項式類存儲爲單項式的鏈表。
我要添加2 polynomials.Here是我除了功能
public Polynomial addition(Polynomial a, Polynomial b) {
LinkedList<Monomial> Main = new LinkedList<>();
LinkedList<Monomial> temp1 = a.getPolynomial();
LinkedList<Monomial> temp2 = b.getPolynomial();
for(int i = 0;i<temp1.size();i++){
for(int j = 0;j<temp2.size();j++){
Integer c1= temp1.get(i).getExp();Integer c2 = temp2.get(j).getExp();
if(c1.equals(c2)){
Float k1 = temp1.get(i).getCoeff();Float k2 = temp2.get(j).getCoeff();
Main.add(new Monomial(k1+k2,temp2.get(j).getExp()));
//temp1.remove(i);temp2.remove(j);
}
else if(!c1.equals(c2)){
Main.add(new Monomial(temp1.get(i).getCoeff(),temp1.get(i).getExp()));
//temp1.remove(i);
Main.add(new Monomial(temp2.get(j).getCoeff(),temp2.get(j).getExp()));
//temp2.remove(j);
}
}
}
Polynomial ret = new Evaluator(Main);
return ret;
}
我的輸入是這樣的 Polynomial1: 10 1 2 3 11 4 5 6 Polynomial2: 12 1 2 3 13 4 5 6
多項式1可以解釋爲10X(Y^2)(Z^3)等等。
,我得到的輸出是: 22.0 1 2 3 10.0 1 2 3 13.0 4 5 6
這是不希望的output.The計算不預製correctly.I知道什麼是錯我的循環體,但我不知道它是什麼。 我想知道哪裏出了問題,以及如何糾正它。
你應該逐步調試你的代碼,檢查爲什麼循環'for(int i = 0; i
MBo
一個問題可能是'if(c1 == c2)'。這不是**比較對象的**值**,而是檢查兩個對象是否是**相同的對象** - 可能不是您的意思。嘗試使用'c1.equals(c2)'進行值比較。 – OldCurmudgeon