How to resolve Exception in thread "main" java.lang.Nullpointerexception error in my program?

Asked

Viewed 432 times

-1

public class ClassMain {

    public static void main(String[] args) {
        CPessoa[] Pessoas = new CPessoa[10];

        int cont=0, j=0;
        for(int i=0; i<10; i++){
            Pessoas[i] = new CPessoa(Pessoas[j].nome, cont);
        }
        cont++;

        for(int i=0; i<10; i++) {
            Pessoas[i] = new CPessoa(Pessoas[j].nome, cont);
        }

    }
}







import java.util.Random;

public class CPessoa {

    String nome;
    String[] amigos = new String[10];
    int contamigo = 0;

    public CPessoa(String nomeamigo, int cont) {
        if(cont==0) {
        GeraNome();
        }else
        if(cont!=0) {
        AddAmigo(nomeamigo);
        MostrarAmigos();
        }
    }

    public void AddAmigo(String nomeamigo) {
        amigos[contamigo] = nomeamigo;
        contamigo++;
    }

    public void MostrarAmigos(){
        System.out.printf("Amigos de %s:\n", nome);
        for(int i=0; i<10; i++) {
            System.out.printf("%s\n", amigos[i]);
        }
        }


    public void GeraNome(){
        String[] consoante = new String[] {"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"};
        String[] vogal = new String[] {"a","e","i","o","u"};
        String[] consoanteM = new String[] {"B","C","D","F","G","H","J","K","L","M","N","P","Q","R","S","T","V","W","X","Y","Z"};

        for(int i=0; i<6; i++) {
            int gerarcns = new Random().nextInt(21);
            int gerarvg = new Random().nextInt(5);

            if(i==0) {
                this.nome+=consoanteM[gerarcns];
            }else {
                if(i%2==1) {
                    this.nome+=vogal[gerarvg];
                }else {
                    this.nome+=consoante[gerarcns];
                }           
            }
            gerarcns=0;
            gerarvg=0;
        }
    }

}
  • Do not ask a question with code only. Explain your question as detailed as possible. Null Pointer Exception means that you are using an object that is null, in the line that is indicated in Stack trace

  • error is because before using Pessoas[j].nome you do not initialize the Pessoas[j].. but just like @Isac said, the question is misspelled.

1 answer

0

Dude, you created the Cpessoa (People) array and didn’t add any people when you try to access a person through the code Pessoas[j].nome , this error will be made. And there’s still a problem, you’re adding items to the array using the array’s own elements. Something’s not right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.