0

Is there a way to avoid this error java.lang.NullPointerException in array?

I create an array with allocated size. But sometimes it doesn't fill up. And I get the error. How to avoid it?

The code:

public static produktas[] surasti (produktas G[], int n){
    try{
    int x = 0;
    BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
    produktas A[] = new produktas[5]; // size of array, but sometimes it may be 1 element, or two, or etc.
    for (int j=0; j<5; j++){
    System.out.println("Kokio produkto ieskosime?");
    String found = in.readLine();
    for (int i=0; i<n; i++){
        if (found.equals(G[i].gautiPav())){ 
            A[x] = G[i];
            x = x + 1;
        }
    }
} 
return A; 
} catch(IOException ie){
        ie.printStackTrace();
    }
    return null;
}

And I'm asking about how to make dynamical array or smth, so it's not related to that topic.

labasRyta
  • 13
  • 1
  • 5
  • Why don't you use an ArrayList? The ArrayList is dynamic and you don't need to specify the size in advance. – Ambidextrous Nov 21 '16 at 22:39
  • @Ambidextrous I would use it if I would know how. That's why I'm asking here. I'm new to java. `produktas A[] = new produktas[5]; ArrayList produktas = new ArrayList produktas();` why this code isnt working? first one is ok, but not the second. – labasRyta Nov 21 '16 at 22:46
  • Try `ArrayList productList = new ArrayList<>();` and then try `productList.add()` to add elements dynamically. `ArrayList`s are generic, so you have to specify the type, which I assume in this case will be `produktas`. – Ambidextrous Nov 23 '16 at 20:47

0 Answers0