Error Exception in thread "main" java.lang.NullPointerException

-2

So, I'm trying to make a program that adds 2 vectors via Thread , but it gives the following error:

  

Exception in thread "main" java.lang.NullPointerException
      at Soma (Main.java:37)
      at Main.main (Main.java:7)

I wanted to know why this error occurred?

public class Main {
    public static int quantidade = 10;

    public static void main( String[] args ){
        int vet1[]= new int [quantidade];
        int vet2[]= new int [quantidade];
        Soma soma = new Soma(0,0,0);
        for(int i=0; i < quantidade; i++){
            vet1[i]=i;
            vet2[i]=i;
        }   
        for(int i=0; i<quantidade;i++){
            if(i<=3){
                Soma s1 = new Soma(vet1[i], vet2[i], i);
                Thread t1 = new Thread(s1);
                t1.start();
            }else if(i>3 && i<7){
                Soma s2 = new Soma(vet1[i], vet2[i], i);
                Thread t2 = new Thread(s2);
                t2.start();
            }else{
                Soma s3 = new Soma(vet1[i], vet2[i], i);
                Thread t3 = new Thread(s3);
                t3.start();
            }
        }
        System.out.println(soma.getSoma());
    }
}

class Soma implements Runnable {
    private int vetor1[];
    private int vetor2[];
    private int soma;
    private int count;
    public Soma(int vet1, int vet2, int quantiadade){
        this.vetor1[quantiadade] = vet1;
        this.vetor2[quantiadade] = vet2;
        this.count = Main.quantidade;
    }
    public void run(){
        for(int i=0;i < count; i++){
            soma = vetor1[i] + vetor2[i];
        }
    }
    public int getSoma(){
        return soma;
    }
}
    
asked by anonymous 22.08.2016 / 01:17

1 answer

2

The problem is here:

    this.vetor1[quantiadade] = vet1;
    this.vetor2[quantiadade] = vet2;

You need to instantiate the vectors before using them.

public Soma(int vet1, int vet2, int quantiadade) {
    this.vetor1 = new int[100];
    this.vetor2 = new int[100];
    this.vetor1[quantiadade] = vet1;
    this.vetor2[quantiadade] = vet2;
    this.count = Teste.quantidade;
}
    
22.08.2016 / 02:58