The following code does not flag compilation errors, but when I call the method darDeAlta()
and enter data, it flags the following error:
Exception in thread "main" java.lang.NullPointerException
In the line d[i] = y.nextDouble();
(within the method) and in the line bandera = e.darDeAlta();
(within the main), I already initialized the array of doubles with null
and I don't understand why it gives me that error.
public class Ejercicio {
Map<Integer, Alumno> alumnos = new TreeMap<>();
public boolean darDeAlta() {
Scanner y = new Scanner(System.in);
boolean b = false;
double d[] = null;
System.out.println("Introduzca el nombre del estudiante");
String n = y.nextLine();
System.out.println("Introduzca su matricula (de 5 digitos)");
int m = y.nextInt();
System.out.println("Introduzca las calificaciones: \n");
for (int i = 0; i < 5; i++) {
System.out.println("Introduzca la calificacion");
d[i] = y.nextDouble();//marca error aqui
}
if (alumnos.containsKey(m)) {
System.out.println("Esa matricula ya existe, ingrese otra matricula");
} else {
alumnos.put(m, new Alumno(n, m, d));
System.out.println("Se han dado de alta los datos :)");
System.out.println("Desea ingresar mas alumnos?");
String s = y.nextLine();
if (s.equals("si")) {
b = true;
} else {
b = false;
}
}
return b;
}
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
boolean bandera = false;
Ejercicio e = new Ejercicio();
do {
System.out.println("[a]ltas" + "\n" + "[b]ajas" + "\n" + "[c]onsultas" + "\n" + "[m]odificaciones" + "\n" + "[s]alir");
System.out.println("\n Seleccione una opcion");
String opcion = x.next();
if (opcion.compareTo("a") == 0) {
bandera = e.darDeAlta();//marca error aqui
}
if (opcion.compareTo("b") == 0) {
e.darDeBaja();
if (opcion.compareTo("c") == 0) {
e.consultas();
if (opcion.compareTo("m") == 0) {
e.modificaciones();
if (opcion.compareTo("s") == 0) {
bandera = false;
}
}
}
}
} while (bandera);
}
}
You haven't initialized the object
d[]
:You must initialize it: