我有一個名爲Polynomial的類,它由一個由名詞對象組成的ArrayList,在我的測試類中有一個由Scanner對象讀取的外部文件。掃描儀讀取4個不同關鍵字的行並相應地執行操作。恩。 INSERT 3 2.將調用我的插入方法並打印出3x^2。現在我有一個帶有兩個參數的刪除方法。當我在測試類中調用方法時,什麼也沒有發生,同樣的事情被打印出來,沒有任何東西被刪除。我是否錯過了一些東西,或者一起做錯了嗎?任何幫助是極大的讚賞。ArrayList不打印移除的對象
public void delete (int coeff, int expo)
{
for (int i = 0; i<terms.size(); i++)
{
Term current = terms.get(i);
terms.remove(current.getCoeff());
terms.remove(current.getExpo());
}
}
我也有一個Term類創建一個術語對象,並有兩個方法來獲取係數和指數。
這裏是我的測試類的一個片段:
public static void main(String[] args) throws IOException
{
// TODO code application logic here
Polynomial polyList = new Polynomial();
Scanner inFile = new Scanner(new File("operations2.txt"));
while(inFile.hasNext())
{
Scanner inLine = new Scanner(inFile.nextLine());
String insert = inLine.next();
if(insert.equals("INSERT"))
{
int coeff = inLine.nextInt();
int expo = inLine.nextInt();
polyList.insert(coeff, expo);
}
if(insert.equals("DELETE"))
{
int coeff = inLine.nextInt();
int expo = inLine.nextInt();
polyList.delete(coeff, expo);
}
}
System.out.println(polyList.toString());
}
}
編輯:這是由掃描儀讀取類.txt文件的樣本:
INSERT 3 2
INSERT 4 4
INSERT 1 6
INSERT 2 0
INSERT 5 2
INSERT 6 3
PRODUCT
DELETE 3 2
INSERT 2 7
DELETE 4 4
INSERT 4 10
編輯:這裏是術語類別:
class Term
{
//instance vars
private int coefficient;
private int exponent;
public Term(int coeff, int expo)
{
coefficient = coeff;
exponent = expo;
}
public int getCoeff()
{
return coefficient;
}
public int getExpo()
{
return exponent;
}
@Override
public int hashCode()
{
return coefficient + exponent;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Term))
{
return false;
}
Term t = (Term)o;
return coefficient == t.coefficient && exponent == t.exponent;
}
}
我實際上已經嘗試過'term.remove(new Term(coeff,expo));'但是沒有任何東西在更新列表中被刪除或替換。基本上我只是打印兩次相同的列表。 – PeterLion 2013-04-21 23:20:13
您必須重寫Term類中的equals()方法。我保證它會起作用。 – Bohemian 2013-04-21 23:22:26
'terms.equals(新術語(coeff,expo));'沿着這些線? – PeterLion 2013-04-21 23:23:31