Error:java.lang.Nullpointerexception at user.Mein.main(Mein.java:15)

Asked

Viewed 49 times

-1

Can someone enlighten me a little, is giving error in the line where I start to fill the user array.

public Usuario(String nome, String sobrenome, String cargo,int idade,double salario) {
    this.nome = nome;
    this.sobrenome = sobrenome;
    this.cargo = cargo;
    this.idade = idade;
    this.salario = salario;
}

public void promover(double porcentagem) {
    this.salario += salario*porcentagem/100;
}


public double getSalario() {
    return salario;
}

public void setSalario(double salario) {
    this.salario = salario;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getSobrenome() {
    return sobrenome;
}

public void setSobrenome(String sobrenome) {
    this.sobrenome = sobrenome;
}

public String getCargo() {
    return cargo;
}

public void setCargo(String cargo) {
    this.cargo = cargo;
}

public int getIdade() {
    return idade;
}

public void setIdade(int idade) {
    this.idade = idade;
}

public String paraString() {
    return "Nome: " + nome + "\n" +
            "Sobrenome: " + sobrenome + "\n" +
            "Idade : " +idade + "\n" +
            "Cargo: " + cargo + "\n" +
            "Id: " + ID + "\n" +
            "Salario: " + salario;
}
public String toString() {
    return "Usuario [salario=" + salario + ", nome=" + nome + ", sobrenome=" + sobrenome + ", cargo=" + cargo
            + ", id=" + ID + ", idade=" + idade + "]";
}

public static void main(String[] args) {  
    Scanner s = new Scanner(System.in);  
    Usuario[] user = new Usuario[5];  
    int i;  
    int porcentagem,id_cont=1;

     for(i=0;i<5;i++){
        System.out.println("Usuario " +i+ ", preencha seus dados, por favor!\n");
        System.out.println("Seu id será gerado automaticamente\n");
        System.out.println("Nome");
        user[i].ID = id_cont++;
        user[i].setNome(s.nextLine());
        System.out.println("Sobrenome");
        user[i].setSobrenome(s.nextLine());
        System.out.println("Cargo");
        user[i].setCargo(s.nextLine());
        System.out.println("Idade");
        user[i].setIdade(s.nextInt());
        s.nextLine();
        System.out.println("Salario");
        user[i].setSalario(s.nextDouble());
        s.nextLine();

        i++;
     }



    System.out.println("Digite a porcentagem de aumento dos usuarios");
    while(i<5) {
        porcentagem = s.nextInt();
        user[i].promover(porcentagem);
        porcentagem = 0;
        i++;
    }



    while(i<5) {
        System.out.println(user[i].paraString());
        System.out.println(user[i].toString());
        i++;
    }


    s.close();


}
  • Hello, enter the code in the question and not the print of your screen. There is the option to insert code.

  • 1

    Okay, thanks for telling me

1 answer

1


Your code has some problems, the first problem and that was described in your question is in the method main on the following lines:

System.out.println("Nome");
user[i].ID = id_cont++;
user[i].setNome(s.nextLine());

What happens is that when you instantiate an array like you do in Usuario[] user = new Usuario[5]; only the memory space is instantiated and not the objects themselves so you need to instantiate a User object, fill it with the data and only then insert the object into the array.

Another problem is that you put i++ in the last line of his for but the directive for already makes the variable increment to each interaction as you can see on the line for(i=0;i<5;i++). In your code for having a i++ at the end of for with each interaction it will increase 2 in the variable i which will cause a IndexOutOfBoundsException.

The last problem lies in your instructions while(i < 5), the problem here is that you use the same control variable you used in for but at this point the value of i should be 6 as it was increased during the execution of the for soon the while(i < 5) will always be false and will never be executed, to correct just reset the value of the variable with 0.

Your code with the proper fixes would look like this:

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    Usuario[] user = new Usuario[5];
    int i;
    int porcentagem, id_cont = 1;

    for (i = 0; i < 5; i++) {
        System.out.println("Usuario " + i + ", preencha seus dados, por favor!\n");
        System.out.println("Seu id será gerado automaticamente\n");

        // Instancia o objeto usuario
        Usuario usuario = new Usuario();

        // Define os valores para o objeto usuario
        System.out.println("Nome");
        usuario.ID = id_cont++;
        usuario.setNome(s.nextLine());

        System.out.println("Sobrenome");
        usuario.setSobrenome(s.nextLine());

        System.out.println("Cargo");
        usuario.setCargo(s.nextLine());

        System.out.println("Idade");
        usuario.setIdade(s.nextInt());
        s.nextLine();

        System.out.println("Salario");
        usuario.setSalario(s.nextDouble());
        s.nextLine();

        // Define esta instancia do objeto Usuario para o indice i do array
        user[i] = usuario;
    }

    // Reinicializa a variavel de controle i
    i = 0;
    System.out.println("Digite a porcentagem de aumento dos usuarios");
    while (i < 5) {
        porcentagem = s.nextInt();
        user[i].promover(porcentagem);
        porcentagem = 0;
        i++;
    }


    // Reinicializa a variavel de controle i
    i = 0;
    while (i < 5) {
        System.out.println(user[i].paraString());
        System.out.println(user[i].toString());
        i++;
    }

    s.close();

}

For the above code to work implement the default constructor with no arguments in its User class:

// Construtor padrao sem argumentos
public Usuario() {

}

Finally a suggestion, use the instruction for when you know the maximum number of repetitions and use the instruction while when I didn’t know the maximum amount of interactions. In your code, for example, the repetition instructions always run 5 times soon a for would be more appropriate.

  • 1

    Thank you very much, you helped me a lot!

Browser other questions tagged

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