Java.lang.ArrayIndexOutOfBoundsException: 5

Résolu
Bonjour,
mon exercice est la suivant:

écrire une action qui affiche les n premiers éléments de la suite définie par

u0=1 et un+1=somme de k=0 jusqu’à n de (uk*un-k)

lors de l'exécution mon prg donne un message suivante

Entrez un no10
2, 3, 4, Exception in thread "main" 5, 6, 7, 8, 9, 10, java.lang.ArrayIndexOutOfBoundsException: 10
at Suite.main(Suite.java:27)
veuillez m'aidez svp
import java.util.Scanner;
public class Suite
{
 public static void main(String[] args) 
 {
  int i=0;
  Scanner sc=new Scanner(System.in);
  System.out.print("Entrez un no");
  int nb=sc.nextInt();
  int []toto=new int[nb];
      toto[0]=1;
    
     /* for( i=1;i<toto.length;i++)
      {
       System.out.print("Entrez un no");
          toto[i]=sc.nextInt();
      }*/
      
     // int[]d=new int[nb];
    //  toto[i]=0;
   
       for(i=1; i<toto.length-1;i++)
          {
          //toto[i]=0;
           for(int j=0; j<toto.length-1;i++)
           {
            toto[i]=toto[i]+toto[j]+toto[i-1-j];
            System.out.print(toto[i]+", ");
           }
          }
 }
}



3 réponses

  1. Modérateur
    Bonjour,

    De manière générale, une "ArrayIndexOutOfBoundsException: x" signifie que l'on a un tableau auquel on accède en faisant
    [x]
    alors que
    x
    est soit négatif, soit plus grand que la taille du tableau (ou égal), car seuls les indices de 0 à length-1 sont autorisés.

    Remarque : je t'invites à bien séparer ton code, en faisant des méthodes intermédiaires, quitte à faire des méthodes de 2 ou 3 lignes seulement.
    Cela simplifie le code en séparant bien chaque étape et en clarifiant le rôle de chaque variable (k, n...) pour éviter de se tromper d'indices et générer des dépassements de tableaux.

    Exemple :

    public static int produit(int[] u, int k, int n) {
        return u[k] * u[n - k];
    }
    
    public static int somme(int[] u, int n) {
        int s = 0;
        for (int k = 0; k < n; k++)
            s += produit(u, k, n-1);
        return s;
    }
    
    public static int[] suite(int length) {
        int[] u = new int[length];
        u[0] = 1;
        for (int n = 1; n < length; n++)
            u[n] = somme(u, n);
        return u;
    }
    
    public static void affichage(int[] u) {
        for (int i = 0; i < u.length; i++)
            System.out.printf("u[%d]=%d\n", i, u[i]);
    }
    
    public static int readInt() {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
        return n;
    }
    
    public static void main(String[] args) {
        System.out.print("Length: ");
        int length = readInt();
        int[] u = suite(length);
        affichage(u);
    }

    Pour info : cette suite correspond aux nombres de Catalan
    1. Bonjour !

      J'aurais plutôt vu ça :
      public static void main (String[] args) {
        final Scanner sc = new Scanner(System.in);
        System.out.print("Saisir la taille de la liste : ");
        int nb = sc.nextInt();
        int[] toto = new int[nb];
        toto[0]=1;
      // remplacé toto.length-1 par toto.length (on a un < au lieu d'un <=, donc 
      // toto.length ne sera jamais affecté à i
        for(int i=1 ; i<toto.length ; i++) {
      // remplacé i++ par j++
      // même modif que la première boucle for
         for(int j=0 ; j<toto.length ; j++) {
      // TODO : i-1-j donne toujours 0 ;-)
          toto[i] = toto[i] + toto[j] + toto[i-1-j];
          System.out.print(toto[i]+", ");
         }
        }
       }


      C'est tout pour moi ;-)

      bonne journée !

      Luc
      Les 3 plus grands mensonges du dev : 1. La doc ? On la fera plus tard... 2. Le programme a été testé et ne comporte aucun bug... 3. Les spécifications techniques sont finies...
      1. en corrigeant erreur comme tu m'avais dit
        je trouve la même erreur
        cette fois celui ci:

        Entrez un no5
        2, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at Suite.main(Suite.java:27)
      2. @domxalineTu as bien remplacé toute la méthode main par celle que je t'ai fournie en faisant copier-coller ? Sinon, vu les modifs que j'ai faites, c'est le jeu des 7 différences qui t'attend ;-)
        Refais le Ctrl-C/Ctrl-V dans le doute ^^
        ... je regarde quand même le code, en attendant ta réponse

        EDIT :

        Piti test :
        Essaie de remplacer l'affectation de variable
        toto[i] = toto[i] + toto[j] + toto[i-1-j];

        par
        toto[i+1] = toto[i] + toto[j] + toto[i-1-j];

        sinon, toto[j] ne devrait pas marcher.
      3. import java.util.Scanner;
        public class Suite1 
        {
        	public static void main(String[] args) 
        	{
        	final Scanner sc = new Scanner(System.in);
        	   int i=0;
        	  //System.out.print("Saisir la taille de la liste : ");
        	 // int nb = sc.nextInt();
        	  int[] toto = new int[5];
        	  for( i=1;i<toto.length;i++)
              {
            	  System.out.print("Entrez un no");
                  toto[i]=sc.nextInt();
              }
        	  toto[0]=1;
        	// remplacé toto.length-1 par toto.length (on a un < au lieu d'un <=, donc 
        	// toto.length ne sera jamais affecté à i
        	  for(i=1 ; i<toto.length-1 ; i++) {
        	// remplacé i++ par j++
        	// même modif que la première boucle for
        	   for(int j=0 ; j<toto.length-1 ; j++) {
        	// TODO : i-1-j donne toujours 0 ;-)
        	    toto[i+1] = toto[i] + toto[j] + toto[i-1-j];
        	    System.out.print(toto[i]+", ");
        	   }
        	  }
        	 }
        }
        

        rien est changé toujours la même erreur
        Entrez un no4
        Entrez un no5
        Entrez un no9
        Entrez un no7
        4, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at Suite1.main(Suite1.java:24)
      4. @domxalineRecompile la classe (ou le projet dans lequel elle est). La ligne 24 est un commentaire ;-)
        Ensuite, relance le main.
        Je ne trouve pas l'erreur...