我有一个名为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