1

I'm quite new to Java, and i meet my first problem. I cannot acces Arrays of Objects, coz of ArrayIndexOutOfBoundsException. It happends even when i hard code creating array of lenght 3, and try to access data in first spot. Could you tell me guys where i have a bug? Putting that block in try/catch doesnt help. I add code of 2 classes, which second is arrays of first. Third code is test. Compilator info

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Zamowienie.dodajPozycje(Zamowienie.java:23)
    at main.main(main.java:12)

public class Pozycja {
String nazwaTowaru;
int ileSztuk;
double cena;

public Pozycja(){
    this.nazwaTowaru = "";
    this.ileSztuk = 0;
    this.cena = 0;
}
public Pozycja(String nazwaTowaru, int ileSztuk, double cena){
    this.nazwaTowaru = nazwaTowaru;
    this.ileSztuk = ileSztuk;
    this.cena = cena;
}

public double obliczWartosc(){
    return ileSztuk*cena;
}
public String toString(){
    return nazwaTowaru+"                    "+cena+" zł     "+ileSztuk+" szt.     "+ileSztuk*cena+" zł";
}
}

public class Zamowienie {
int ileDodanych;
int maksRozmiar;
int x;
Pozycja[] tab = new Pozycja[maksRozmiar];




public Zamowienie(){
maksRozmiar = 10;
ileDodanych = 0;

}
public Zamowienie(int maksRozmiar){
    this.maksRozmiar = maksRozmiar;
    ileDodanych = 0;

}
public void dodajPozycje(Pozycja p){

    tab[ileDodanych]= new Pozycja();

    ileDodanych++;


}
public double ObliczWartosc(){
    int i=0;
    double suma=0;
    while (i<ileDodanych){
    suma = suma+tab[i].cena*tab[i].ileSztuk;
    i++;    
    }
    return suma;

}
public String toString(){
    int i=0;
    double suma=0;
    String calosc = new String("");
    while (i<ileDodanych){
    suma = suma+tab[i].cena*tab[i].ileSztuk;
    i++;    
    }
    i=0;
    while (i<ileDodanych){
        calosc= tab[i].nazwaTowaru+String.valueOf(tab[i].ileSztuk)+" szt.     ";
        i++;
    }
        return calosc;

}
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Panczaq
  • 11
  • 2
  • I'm not sure how to edit, so - in public void dodajPozycje(Pozycja p) there is missing tab[ileDodanych] = p; in second line – Panczaq Dec 14 '16 at 23:05
  • Click on the edit link under your post or on [this link](http://stackoverflow.com/posts/41153759/edit) – Hovercraft Full Of Eels Dec 14 '16 at 23:06
  • 2
    and yes your question is a complete duplicate of the one used to close this question. You're creating an array with 0 elements, and so any time you try to add anything to it, this exception will be thrown. The solution is not to do this, to make your array big enough -- or to use an ArrayList. – Hovercraft Full Of Eels Dec 14 '16 at 23:46
  • What you want to do is in your constructor, set the `maksRozmiar` variable, **and then create the array at this time, using the non-0 maksRozmiar value**. – Hovercraft Full Of Eels Dec 14 '16 at 23:47

0 Answers0