gpt4 book ai didi

java - 为什么会抛出空点异常?

转载 作者:行者123 更新时间:2023-12-01 20:27:28 25 4
gpt4 key购买 nike

出于某种原因,每当我对此进行测试时,IDE 都会在第 46 行(检查数组名称的 for 循环)抛出 NullPointerException。它似乎有效,因为它获取名称并返回它,但随后立即出现异常。谁能解释一下吗?谢谢!

导入java.util.*;电话号码类{

private String name;
private String number;

PhoneNumbers(String n, String numb) {
this.name = n;
this.number = numb;
}

public String getName() {
return name;
}

public String getNumber() {
return number;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean repeat = true;
int count = 11;
PhoneNumbers[] contacts = new PhoneNumbers[30];

contacts[0] = new PhoneNumbers("Gina", "(847) 342-0912");
contacts[1] = new PhoneNumbers("Marcia", "(847) 341-2392");
contacts[2] = new PhoneNumbers("Rita", "(847) 354-0654");
contacts[3] = new PhoneNumbers("Jennifer", "(414) 234-0912");
contacts[4] = new PhoneNumbers("Fred", "(414) 435-0434");
contacts[5] = new PhoneNumbers("Neil", "(608) 123-0914");
contacts[6] = new PhoneNumbers("Judy", "(608) 123-0312");
contacts[7] = new PhoneNumbers("Arlene", "(608) 123-0312");
contacts[9] = new PhoneNumbers("LaWanda", "(920) 787-9813");
contacts[10] = new PhoneNumbers("Deepak", "(930) 412-0991");

while (repeat) {
boolean found = false;

System.out.print("Enter your friends name: ");
String nameInput = sc.nextLine();

if (!nameInput.equalsIgnoreCase("quit")){

for(int i = 0; i < count - 1; i++){
if (contacts[i].getName().equalsIgnoreCase(nameInput)) {<---Here's where the issue occurs***
found = true;
System.out.println(contacts[i].getName() + "'s number is " + contacts[i].getNumber());
}
}
if (!found){
System.out.println("Enter your friends phone number: ");
String num = sc.nextLine();

contacts[count + 1] = new PhoneNumbers(nameInput, num);
count++;
}
}else if (nameInput.equalsIgnoreCase("quit")) {
repeat = false;
}else if (count == 30){
repeat = false;
}
}
}
}

最佳答案

您在初始化中缺少 contacts[8],因此在尝试访问不存在的联系人 8 的姓名时,您将收到 NullPointerException:

// ...
contacts[7] = new PhoneNumbers("Arlene", "(608) 123-0312");
contacts[9] = new PhoneNumbers("LaWanda", "(920) 787-9813");
// ...

关于java - 为什么会抛出空点异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com