i am not able to add an element to my array list using the operator add in the java polynomial function

Your logic is flawed.

    for (int i = 0; i < terms.size(); i++) {
        if(terms.get(i)...) {
            ... 
        } else {
            terms.add(...);
        }
    } 

If the list is initially empty, this loop will not do anything, and the else clause will also not occur, so no terms ever get added.

A for loop does not have an else clause, but you can use a boolean to fix it:

   boolean found = false;
   for (int i = 0; i < terms.size(); i++) {
        if(terms.get(i)...) {
            ... 
            found = true;
        }
    }  
    if (!found) {
        terms.add(...);            
    } 

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top