I wrote this program:
public class FunctionEvaluator {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int degree;
System.out.print("What degree would you like your polynomial to be? ");
degree = console.nextInt();
int a[] = new int[degree + 1];
int coefficient;
for (int i = 0; i <= degree; i++) {
System.out.print("Coefficient of the x^" + (degree - i) + " term: ");
coefficient = console.nextInt();
a[i] = coefficient;
}
System.out.print("f(x) = ");
for (int i = 0; i < degree + 1; i++) {
System.out.print(a[i] + "x^" + (degree - i));
if (a[i] == degree) {
System.out.println(" ");
} else if (a[i + 1] >= 0 && a[i + 1] < degree) {
System.out.print(" + ");
} else if (a[i] < 0) {
System.out.print(" - ");
} else {
System.out.print(" ");
}
}
System.out.println();
int x;
int yN = 0;
double fOfX = 0;
double sum1;
do {
System.out.print("Give a value for x: ");
x = console.nextInt();
int deg = degree;
for (int i = 0; i <= degree; i++) {
sum1 = a[i] * Math.pow(x, deg);
deg--;
fOfX = fOfX + sum1;
}
System.out.println("f(" + x + ") = " + fOfX);
System.out.print("Do you want to go again (1 for yes and 0 for no)? ");
yN = console.nextInt();
} while (yN == 1);
System.out.println("Done.");
}
And there's a problem with this code:
System.out.print("f(x) = ");
for (int i = 0; i < degree + 1; i++) {
System.out.print(a[i] + "x^" + (degree - i));
if (a[i] == degree) {
System.out.println(" ");
} else if (a[i + 1] >= 0 && a[i + 1] < degree) {
System.out.print(" + ");
} else if (a[i] < 0) {
System.out.print(" - ");
} else {
System.out.print(" ");
}
}
The main code is supposed to ask the user for a degree of polynomial and the coefficients and then do some math. If I comment out the above segment of code, the program works fine. However, when I leave the above code in (it's supposed to print out the function), the program crashes. I suspect it has something to do with the limits on the for loop but no matter what I change or modify, the program still crashes. Could anybody tell me what's wrong and why the program won't run? IntelliJ is telling me that the problem is on the first else if line or the nested if statement in the for loop if that helps.