2012-11-16 58 views
3

我叫長期持有多項式像下面的Java/JUnit的 - 比較兩個多項式對象

public Term(int c, int e) throws NegativeExponent { 
    if (e < 0) throw new NegativeExponent(); 
    coef = c; 
    expo = (coef == 0) ? 1 : e; 
} 

我也有在同一類的equals方法如下面

@Override 
public boolean equals(Object obj) { 

} 

我是一個Java類如何編碼如何比較這兩個術語對象

在我的JUnit測試文件中,我使用以下測試來嘗試和測試等於方法

import static org.junit.Assert.*; 

import org.junit.Test; 

public class ConEqTest 
{ 
    private int min = Integer.MIN_VALUE; 
    private int max = Integer.MAX_VALUE; 



@Test 
public void eq01() throws TError { assertTrue(new Term(-10,0).equals(new Term(-10,0))); } 

@Test 
public void eq02() throws TError { assertTrue(new Term(0,0).equals(new Term(0,2))); } 
+1

你可能要考慮rnaming'NegativeExponent'到'NegativeExponentException'代替,只是作爲一個備用。 – arshajii

+0

確保你也有一個hashcode()。 –

+0

要添加@RayTayek的評論請參閱[此解釋](http://stackoverflow.com/a/27609/18573)爲什麼有必要 –

回答

5

這有什麼錯

@Override 
public boolean equals(Object obj) { 
    if (! (obj instanceof Term)) 
     return false; 
    Term t = (Term)obj; 
    return coef == t.coef && expo == t.expo; 
} 
+0

感謝您的答覆A.R.S 我已經確定,啓動它的方式的確與 'code'if(!(obj instanceof Term)) return false; 期限t =(期限)obj; 但是最後一部分不適用於我,我沒有方法稱爲coef()和expo(),所以我不完全確定如何去比較兩個Term對象 – germainelol

+0

@ user1828314'coef'和'expo'字段'公共'? – arshajii

+0

我已經在課程頂部定義了它們: \t'final private int coef; \t final private int expo;' 不知道如何去使用它來比較所有對象 – germainelol

1
import static org.junit.Assert.*; 
import org.junit.*; 
@SuppressWarnings("serial") class NegativeExponentException extends Exception {} 
class Term { 
    @Override public int hashCode() { 
     final int prime=31; 
     int result=1; 
     result=prime*result+coefficient; 
     result=prime*result+exponent; 
     return result; 
    } 
    @Override public boolean equals(Object obj) { 
     if(this==obj) 
      return true; 
     if(obj==null) 
      return false; 
     if(getClass()!=obj.getClass()) 
      return false; 
     Term other=(Term)obj; 
     if(coefficient!=other.coefficient) 
      return false; 
     if(exponent!=other.exponent) 
      return false; 
     return true; 
    } 
    public Term(int c,int e) throws NegativeExponentException { 
     if(e<0) 
      throw new NegativeExponentException(); 
     coefficient=c; 
     exponent=(coefficient==0)?1:e; 
    } 
    int coefficient,exponent; 
} 
public class So13408797TestCase { 
    @Test public void eq01() throws Exception { 
     assertTrue(new Term(-10,0).equals(new Term(-10,0))); 
    } 
    @Test public void eq02() throws Exception { 
     assertTrue(new Term(0,0).equals(new Term(0,2))); 
    } 
    private int min=Integer.MIN_VALUE; 
    private int max=Integer.MAX_VALUE; 
}