一个ArrayList所以我就来回好几次尝试多种不同的方法,但我似乎无法环绕此方法的适当的算法我的头。我创建了一个使用ArrayList的Polynomial类,其中Term(int coeff,int expo)coeff是多项式的系数,expo是指数。在测试类中,我必须插入多个不同的Term对象,但它们需要按其指数以升序插入(例如,4x^1 + 2x^3 + x^4 + 5x^7)插入升序排列的对象与Java中
这是代码我有最多这需要两个参数,系数_和博览会插入件()方法的末尾:
public class Polynomial
{
private ArrayList<Term> polynomials ;
/**
* Creates a new Polynomial object with no terms
*/
public Polynomial()
{
polynomials = new ArrayList<>() ;
}
/**
* Inserts a new term into its proper place in a Polynomial
* @param coeff the coefficient of the new term
* @param expo the exponent of the new term
*/
public void insert(int coeff, int expo)
{
Term newTerm = new Term (coeff, expo) ;
if (polynomials.isEmpty())
{
polynomials.add(newTerm);
return;
}
int polySize = polynomials.size() - 1 ;
for (int i = 0 ; i <= polySize ; i++)
{
Term listTerm = polynomials.get(i) ;
int listTermExpo = listTerm.getExpo() ;
if (expo <= listTermExpo)
{
polynomials.add(i, newTerm);
return;
}
else if (expo > listTermExpo)
{
polynomials.add(newTerm) ;
return ;
}
}
}
问题出现靠近代码的末尾。一旦我放入一个其系数不是< = Term的索引,它将转到else if语句并将其添加到列表的末尾。这是错误的,因为它需要被添加到只比下一个系数更大的地方。仅仅因为它大于该系数并不意味着它的最大系数。我试着for语句做向后其中:
for (i = polySize ; i >= 0 ; i--)
{
etc.
}
但是,这并没有工作,要么因为它提出了同样的问题,只是周围的其他方法。如果任何人可以提供一些解决方案或答案,将非常感激,因为我很困惑。在这一点上,我确信我只是让它太复杂了。我只想知道如何识别指数较大,但随后回到for循环,直到它小于或等于索引的指数。
另外,我应该提,我不能使用任何其他集合或类,所以我必须使用的,如果做到这一点,否则,或while语句做。 在此先感谢!之后的for循环
else if (expo > listTermExpo)
{
polynomials.add(newTerm);
return;
}
地点是::
所以才要总结这一切时,你问如何通过将期限与ArrayList的索引为0的最大系数进行排序的ArrayList,以及第二大的指数1等..? – 2013-04-18 02:23:07
没有实际相反,我想把期限与该ArrayList年底最大的指数,在指数的ArrayList 0最小的指数,该系数在多项式 – 2013-04-18 02:26:49