schapman22
- 74
- 0
Homework Statement
We must make a class used to evaluate a polynomial function of x. My problem is I am getting an array out of bounds exception when I run the main, and I can't figure out why.
If you could help me figure out this out of bounds exception it would be very appreciated thank you.
Homework Equations
ex. P(x)= a0 + a1x + a2x2...
The Attempt at a Solution
This is the class
Code:
public class Polynomial
{
private int degree, i=0, size;
private double answer;
private double[] coefficient = new double[size];
public Polynomial(int max)
{
if(degree>=0)
degree = max;
size=max+1;
}
public void setConstant(int subscript, double value)
{
i = subscript;
coefficient[i] = value;
}
public double evaluate(int x)
{
for(int index=0;index<coefficient.length;index++)
{
answer = coefficient[index] * (Math.pow(x, degree));
}
return answer;
}
}
This is the main
Code:
public class PolynomialDemo
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Polynomial p = new Polynomial(3);
p.setConstant(0, 3);
p.setConstant(1, 5);
p.setConstant(2, 0);
p.setConstant(3, 2);
System.out.println(p.evaluate(7));
}
}
Last edited: