The following problem appears in my console after I execute the code and introduce the first cota l[i].cota = sc.nextLine()
;
Exception in thread "main" java.lang.NullPointerException
at exercicio6.introlivros(exercicio6.java:18)
at exercicio6.main(exercicio6.java:9)
can anyone tell me what's the issue?
Here is my code
public class exercicio6 {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
livro l[] = new livro[200];
l = introlivros();
apagarbase(l);
}
public static livro[] introlivros() {
int i = 0;
livro l[] = new livro[200];
do {
System.out.print("Introduza a cota:");
l[i].cota = sc.nextLine();
if (l[i].cota.length() == 0)
break;
do {
System.out.print("Introduza o autor:");
l[i].autor = sc.nextLine();
} while (l[i].autor.length() < 40);
System.out.print("Introduza o titulo:");
l[i].titulo = sc.nextLine();
System.out.println("Introduza a data:");
System.out.println("Dia:");
l[i].data[0] = sc.nextInt();
System.out.println("Mes:");
l[i].data[1] = sc.nextInt();
System.out.println("Ano:");
l[i].data[2] = sc.nextInt();
i++;
} while (i < 200);
return l;
}
public static void remover(livro l[]) {
String cota1 = new String();
boolean verificar = false;
do {
cota1 = sc.nextLine();
if (cota1.length() != 0) {
for (int i = 0; i < 200; i++) {
if (cota1 == l[i].cota) {
l[i].cota = "";
break;
}
if (cota1 != l[i].cota) {
verificar = true;
}
}
}
if (cota1.length() == 0) {
System.out.println("Introduza a cota de novo!");
}
if (verificar == true) {
System.out.println("Esse livro não eciste!");
}
} while (cota1.length() == 0);
}
public static void apagarbase(livro l[]) {
livro p[] = new livro[200];
for (int i = 0; i < 200; i++) {
l[i].cota = null;
l[i].autor = null;
l[i].titulo = null;
l[i].data[0] = 0;
/*
* l[i].data[1]=null; l[i].data[2]=null; l[i].estado[0]=null;
*/
}
}
}
class livro {
String cota = new String();
String autor = new String();
String titulo = new String();
int data[] = new int[3];
char estado[] = new char[1]; // Requisitado R, Livre L, Condicionado C;
}
Here you are instantiating your array:
livro l[] = new livro[200];
However here you are attempting to access an element containing an object that does not exist yet:
l[i].cota = sc.nextLine();
You need to loop through and instantiate a new object at EVERY element. Either use a for loop or Array.fill.
As stated above - objects are initialized to null
A quick way of populating an array is -
livro l[] = new livro[200];
Arrays.fill(l, new livro());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.