将术语插入具有Degree的降序多项式。 (JAVA)

问题描述 投票:1回答:2

对于我的任务,我需要使用由Term(我们之前在类中创建的类,例如:7x ^ 5)组成的ArrayList创建一个多项式类。我需要这样做,以便当术语插入ArrayList时,它们按降序排序。

这是我的代码:

public void insert(Term aTerm)
{
    Term tempTerm = new Term(0,0); //term of 0x^0 that is used to set the term to 0 after its added.

    if(aTerm == null)
        throw new IllegalArgumentException("The inserted term cannot be null.");
    else if(aTerm.isZero() == true)
        aTerm.degree(); //PLACEHOLDER not sure what to do here in order to not insert aTerm
    else if(aTerm.degree() > theAL.get(0).degree()) 
        theAL.add(0, aTerm); //adds to position 0 if largest degree
    else if(aTerm.degree() < theAL.get(theAL.size() - 1).degree())
        theAL.add(theAL.size() - 1, aTerm); //adds to the last position if it is the smallest degree
    else
        for(int i = 0; i < theAL.size(); i++)
        {
            if(aTerm.isZero() == true)
                i = theAL.size(); //ends the for loops whenever aTerm is added and set = to 0
            else if(aTerm.degree() < theAL.get(i).degree() && aTerm.degree() > theAL.get(i + 1).degree())
            {
                theAL.add(i + 1, aTerm);  //adds between 2 terms if less than 1st term and greater than 2nd term.
                aTerm.multiplyBy(tempTerm); //makes the term = zero so that the for loop can end after being added.
            }
            else if(aTerm.degree() == theAL.get(i).degree())
            {
                aTerm.addIn(theAL.get(i)); //adds into the term if the degrees are equal
                aTerm.multiplyBy(tempTerm);//makes the term = zero so that the for loop can end after being added.
            }
        }

}

如果该项为0,我不希望它被添加到多项式中,但正如您在我的代码中所看到的,我不确定我应该在那里做什么以便不插入它,所以我只是在那里放置一个占位符。有什么想法我应该在那里做什么?

当我通过我的Instructors测试程序放入我的代码时,它会在尝试添加术语时抛出一堆OutOfBoundsException。

我理解OutOfBoundsException是什么,但我不确定是什么导致它在每个场景中超出界限。我知道我的代码可能需要很多工作,但如果有人能给我一些建议,我会非常感激。我努力想办法把它放在一起,特别是当我到达使用for循环遍历多项式的部分时,我一直在努力。

谢谢你的帮助。

编辑:

学期分类:

public class Term implements TermInterface

//-------data
private int coefficient;
private int power;


//------constructors
//default constructor
public Term()
{
    this.coefficient = 2;
    this.power = 3;
}
//parameterized constructor
public Term(int aCoefficient, int aPower)
{
    this.coefficient = aCoefficient;
    this.power = aPower;
}
//copy constructor
public Term(Term aTerm)
{
    if(aTerm != null)
        {
        this.coefficient = aTerm.coefficient;
        this.power = aTerm.power;
        }
    else
        throw new IllegalArgumentException("Term cannot be null");
}

//------methods

// toString() - returns its representation as a String   3x^2   for example,
    public String toString()
    {
        if(this.coefficient == 0)
            return "0";
        else if(this.power == 0)
            return(this.coefficient + "");
        else if(this.coefficient == 1 && this.power == 1)
            return "x";
        else if(this.coefficient == -1 && this.power == 1)
            return "-x";
        else if(this.power == 1)
            return(this.coefficient + "x");
        else if(this.coefficient == 1)
            return("x^" + this.power);
        else if(this.coefficient == -1)
            return("-x^" + this.power);
        else
            return(this.coefficient + "x^" + this.power);
    }

//degree -  if coefficient is 0, then (it is a constant so) returns 0.
//                  else returns the power

public int degree() 
{
    if(this.coefficient == 0)
    {
        return 0;
    }
    else
        return power;
}

//evaluate - evaluates with whatever double is received
public double evaluate(double value)
{
    return Math.pow(value, power) * this.coefficient;
}

//derivative -  return a new Term that is the derivative.   The derivative
//                      is calculated by:
//                          the coefficient of the derivative is the original coefficient times the power
//                          the power of the derivative is the original power minus 1
public Term derivative()
{
    Term derivative = new Term(this.coefficient * this.power, this.power - 1);
    return derivative;
}

//addIn: add another Term to itself.
//The Term that is received is not changed.
//  if the Term that is received is null, throw a new IllegalArgumentException(<your descriptive String here>)
//  if the powers are not the same, throw a new IllegalArgumentException(<your descriptive String here>)
public void addIn(Term anotherTerm)
{
    if(anotherTerm == null)
        throw new IllegalArgumentException("Term cannot be null");
    else if(this.power != anotherTerm.power)
        throw new IllegalArgumentException("Powers must be equial");
    else
        this.coefficient += anotherTerm.coefficient;        
}

//multiplyBy: multiply itself by anotherTerm - result is a new Term that is created and returned.
//The original Term and the Term that is received are not changed.
//  if the Term that is received is null, throw a new IllegalArgumentException(<your descriptive String here>)
public Term multiplyBy(Term anotherTerm)
{
    if(anotherTerm != null)
        throw new IllegalArgumentException("Term cannot be null");
    else
    {
        Term multiplied = new Term(this.coefficient * anotherTerm.coefficient, this.power + anotherTerm.power);
        return multiplied;
    }

}

public boolean isZero()
{
    if(this.coefficient == 0)
        return true;
    else
        return false;
}

//equals: returns true if it is the same as what is received.
//      If both coefficients are 0, they are automatically equal
//      otherwise, both coefficients AND both exponents must be the same
public boolean equals(Object obj)
{
    if (obj == null)
        return false;
    if (this.getClass() != obj.getClass())
        return false;

    Term objTerm = (Term)obj;

    return(this.power == objTerm.power && this.coefficient == objTerm.coefficient);
}

}

编辑2:最终工作代码:

public void insert(Term aTerm)
{   
    if(aTerm == null)
        throw new IllegalArgumentException("The inserted term cannot be null.");
    else if(aTerm.isZero() == true)
        return;

    int insertIndex = -1;
    int i = 0;
    boolean degreeEqual = false;

    while(insertIndex == -1 && i < theAL.size())
    {
        Term tempTerm = theAL.get(i);
        if(tempTerm.degree() == aTerm.degree())
        {
            degreeEqual = true;
            aTerm.addIn(tempTerm);
            insertIndex = i;
        }
        else if(aTerm.degree() > tempTerm.degree())
            insertIndex = i;//ends the loop because we know where to put insert the term
        i++; //increment index counter
    }

    if(degreeEqual == false)
    {
        if(insertIndex >= 0) //check to make sure index location is valid.
            theAL.add(insertIndex, aTerm);
        else
            theAL.add(aTerm);//insert term at the end because it is less than other terms
    }
    else
    {
        if(insertIndex >= 0) //check to make sure index location is valid.
        {
            theAL.remove(insertIndex);
            theAL.add(insertIndex, aTerm);
            if(theAL.get(insertIndex).isZero())
            {
                theAL.remove(insertIndex);
            }
        }
        else
            theAL.add(aTerm);//insert term at the end because it is less than other terms
    }

}
java methods
2个回答
1
投票

我可以看到你的目标,但是你已经使你的测试和循环变得比需要的复杂得多。我可能会误解算法的意图,但我会简化为这样的事情:

if(aTerm == null || aTerm.isZero()) {
    return;// this is not a valid term
}

int insertIndex = -1; 
int i = 0;
boolean addToList = true;
// loop until you've found your place, make sure to test for end conditions 
// so you don't hit an IndexOutOfBounds error or create an infinite loop
while(insertIndex == -1 && i < theAL.size() && addToList) {
    Term thisTerm = theAL.get(i);
    if(aTerm.degree() == thisTerm.degree()) {
        thisTerm.addIn(aTerm);
        addToList = false;
    } else if(aTerm.degree() > thisTerm.degree()) {
        insertIndex = i;// this will end the loop, we know where to sort 
                        // this element in our array
    }
    i++;// increment our counter
}

if(addToList) {
    // make sure we found a valid location, if so, add in our term
    if(insertIndex >= 0) {
        theAL.add(insertIndex, aTerm);
    } else {
        theAL.add(aTerm); // insert the term at the end, it's less than all 
                          // other terms in the list, or the list is empty
    }
}

0
投票

这条线很可能会导致一些问题:

else if(aTerm.degree() < theAL.get(i).degree() && aTerm.degree() > theAL.get(i + 1).degree())

您尝试访问列表中的i + 1元素。因为你的迭代遍历:

for(int i = 0; i < theAL.size(); i++)

这将导致内存访问“列表大小越大”,因此导致OutOfBoundException。只是我的猜测,直到你可以分享你的Term课程。当列表为空(插入第一个元素之前)时,它也可能是一个问题,因为您访问列表中不存在的0元素。

对于你的其他问题,根据null术语:

else if(aTerm.isZero() == true)
    aTerm.degree(); 

你可以只是return

else if(aTerm.isZero() == true)
    return; 

如果无事可做,什么也不做。

© www.soinside.com 2019 - 2024. All rights reserved.