user6896477 user6896477 - 2 months ago 9
Java Question

About printing out a polynomial

This is part of a class that store and evaluate a polynomial of input number
And here is the method

public class Polynomial{
int coef,power;

public Polynomial(int maxPower){
}

public void setTerm(int coefficient, int power) {
this.coef = coefficient;
this.power = power;
}


And the input parameters in main method

public static void main(String[] args){
Polynomial q = new Polynomial(2);
q.setTerm(2, 0);
q.setTerm(0, 1);
q.setTerm(3, 2);
System.out.println(q);
}


And There is a toString method to print out the polynomial looks like this

public String toString(){
return
}


I kept encountering the problem where the setTerm method only read the last input parameters which is q.setTerm(3,2), and I think the first two were replaced. What can I do?

Answer

So in your example we have to remember the previously seen terms.

I will do it via a map as the follows.

import java.util.HashMap;
import java.util.Map;

/**
 * Created by arunavs on 9/28/16.
 */
public class Polynomial {

    // Key is power, value is coeff.
    private Map<Integer, Integer> powerToCoeffMap = new HashMap<>();

    // Maximal power allowed for polynomial.
    private int maxPower;


    public Polynomial(int maxPower){
        this.maxPower = maxPower;
    }

    public void setTerm(int coefficient, int power) {
        if (power > maxPower) {
           // throw some exception here. 
        }
        powerToCoeffMap.put(power, coefficient);
    }

    // terms may be rearranged in output. 
    public String toString() {
        StringBuilder builder = new StringBuilder();
        powerToCoeffMap.forEach((power, coeff) -> {builder.append(coeff + "x^" + power+ " ");});
        return builder.toString();
     }

        public static void main(String args[]) {
            Polynomial q = new Polynomial(2);
            q.setTerm(2, 0);
            q.setTerm(0, 1);
            q.setTerm(3, 2);
        System.out.println(q);
    }
}

Outputs : 2x^0 0x^1 3x^2

I hope this helps.

Comments