Lagrange interpolation - ERROR in [do while]

Asked

Viewed 50 times

1

I’m creating a method to catch n values, adding them in an array, and from these values apply the Lagrange interpolation method to find a polynomial. Soon after, find an estimated value of x for the range defined by the largest and smallest value of the inputted data set.

It’s just that you’re making a mistake in while, because he even takes the first value, but when he goes through the first instruction of input he gives the following:

  • ERROR:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 0

at Lagrange.calculate(Lagrange.java:13)

At Main.main(Main.java:6)

Exit status 1

import java.util.Scanner;

public class lagrange{
   public void calculate(){
      Scanner sc = new Scanner(System.in);
      double n[];
      int cont = 0;

      do {
        n = new double[cont];
        System.out.println("Digite o valor de numero " + cont + 1);
        n[cont] = sc.nextDouble(); //INPUT DE DADO NO ARRAY
        cont = cont + 1;
      } while(n[cont - 1] != 0); //continuar o processo até o array for igual a zero

   System.out.println(n[cont-1]);
   }
}

1 answer

1


On the line

int cont = 0;

change to

System.out.println("Digite o grau do polinômio");
int cont = sc.nextInt() + 1;
int indice = 0;

On the line

System.out.println("Digite o valor de numero " + cont + 1);

change to

System.out.println("Digite o valor do coeficiente " + indice);

On the line

n[cont] = sc.nextDouble();

change to

n[indice] = sc.nextDouble();

Remove the line

cont = cont + 1;

On the line

} while (n[cont - 1] != 0);

change to

} while (n[indice++] != 0 && indice < cont); 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.