Я написал эту программу:Распечатка массива Java
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.");
}
И есть проблема с этим кодом:
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(" ");
}
}
Основной код должен спросить пользователя о степени полинома и коэффициенты, а затем выполнить некоторую математику. Если я прокомментирую вышеприведенный сегмент кода, программа работает нормально. Однако, когда я оставляю код выше (он должен распечатать функцию), программа вылетает из строя. Я подозреваю, что это имеет какое-то отношение к ограничениям цикла for, но независимо от того, что я изменяю или изменяю, программа по-прежнему падает. Может ли кто-нибудь сказать мне, что случилось, и почему программа не будет работать? IntelliJ говорит мне, что проблема заключается в первом else, если строка или вложенный оператор if в цикле for, если это помогает.
Какое исключение вызывает сбой? – ostrichofevil
И в какой строке – Gavriel
ArrayIndexOutOfBoundsException я бы догадался. a [i] - это самое высокое, что вы можете сделать. – GoGoCarl