![](/img/trans.png)
[英]Exception in thread “main” java.lang.NullPointerException
[英]Exception in thread “main” java.lang.NullPointerException
執行代碼並引入第一個l[i].cota = sc.nextLine()
之后,控制台中出現以下問題:
線程“主”中的異常java.lang.NullPointerException
在exercicio6.introlivros(exercicio6.java:18)
在exercicio6.main(exercicio6.java:9)
誰能告訴我這是什么問題?
這是我的代碼
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;
}
在這里,您要實例化數組:
livro l[] = new livro[200];
但是,您在此處嘗試訪問包含尚不存在的對象的元素:
l[i].cota = sc.nextLine();
您需要遍歷並在每個元素處實例化一個新對象。 使用for循環或Array.fill。
如上所述,將對象初始化為null
填充數組的一種快速方法是-
livro l[] = new livro[200];
Arrays.fill(l, new livro());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.