jeudi 16 août 2018

how to code a java method that retrieve a given index value?

// this this the orginal code:

public void searchBird (int indexPosition) {
    
     Bird bird = birdList.get (indexPosition);
     System.out.println ("Art:" + bird.getArt ());
     System.out.println ("Location:" + bird.getLocation ());
     }

// Jag har så länge försökt att koda en metod som retunerar ett element ur ArrayList med en angiven index som parameter. Jag får ett felmeddelande när jag skickar in exempelvis 5 som parameter.

// and this is what i tried:

public void searchBird (int indexPosition) {
             Bird bird = birdList.get (indexPosition);
             for (int i = 0; i <bird list.size (); i ++) {
             if ((birdList.contains (indexPosition))) {
             System.out.println ("Art:" + bird.getArt ());
             System.out.println ("Location:" + bird.getLocation ());
                 }
             }
         }

// this is what i get; java.lang.IndexOutOfBoundsException: Index: 5, Size: 3 when calling the method with 5 as a parameter

Aucun commentaire:

Enregistrer un commentaire