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

-2

I just made a program and it marks me the following error:

  

Exception in thread "main" java.lang.NullPointerException at   example_4.Example_4.main (Example_4.java:41)

Code:

import java.util.Scanner;

public class Ejemplo_4 {

public static void main(String[] args) {
        persona []per = new persona[10];
        int contador = 0;
        int opcion = 1;
        String nombre;
        Scanner sc = new Scanner(System.in);
        do{
            do{
                System.out.println("Desea registrar a una persona?\n\t1. SI\n\t2. NO");
                opcion = sc.nextInt();
            }while(opcion<1 || opcion>2);
            System.out.println("Ingrese su nombre:");
            nombre = sc.nextLine();
            per[contador].setNombre(nombre);
            contador++;

        }while(opcion != 1 || contador >= 10);
    }
}

    /* Aqui la clase */
    package ejemplo_4;


public class persona {
    private String nombre;
    private double peso;
    private double altura;

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}
    
asked by Vaca 01.08.2017 в 02:39
source

1 answer

0

You are not initializing the array index per to access them.

You are creating an array with a limit of 10 elements:

persona[] per = new persona[10];

But nowhere in the code you initialize the indexes of the array so when you try to access any index, the array will return a null value and as you try to access a null instance it will throw the NullPointerException . Here is the code that sends you the error:

per[contador].setNombre(nombre);
    
answered by 01.08.2017 / 03:02
source