【发布时间】:2021-07-18 18:15:10
【问题描述】:
我正在尝试创建一个方法来输出仅显示以 030 开头的特定数字的数组,但尚未在 Internet 上找到任何解决方案。 运行程序时显示以下异常:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Contact.setNumber(String)" because "array[i]" is null.
我已经创建了两个类,一个用于 Contact,我将 getter 和 Setter 用于 Number 和 Numerisation,第二类 ContactManagement 用于过滤包含数字的数组(public static Contact[] ShowBerlinsContactList(Contact[] list))
public class ContactManagement {
static Contact N1 = new Contact("1", "0301340711036");
static Contact N2 = new Contact("2", "0301144663311");
static Contact N3 = new Contact("3", "0201629360578");
static Contact N4 = new Contact("4", "0451629360123");
static Contact N5 = new Contact("5", "0303544442103");
static Contact N6 = new Contact("6", "0305344442103");
static Contact N7 = new Contact("7", "0701571456781");
static Contact N8 = new Contact("8", "0701571446781");
public static Contact[] ContactList = new Contact[]{N1, N2, N3, N4, N5, N6, N7, N8};
public static Contact[] ShowBerlinsContactList(Contact[] list) {
Contact[] array = new Contact[list.length] ;
for (int i = 0; i <= list.length; i++) {
String a = list[i].getNumber();
char c0 = a.charAt(0);
char c1 = a.charAt(1);
char c3 = a.charAt(2);
for(int j=0;j<= array.length; j++) {
if ((c0 == '0') && (c1 == '3') && (c3 == '0')) {
array[i].setNumber(a);
}
}
}
return array ;
}
public static void main(String[] args) {
try{
for(int i = 0 ; i <= ContactList.length ; i++) {
System.out.println("N"+(i+1) +":" + ContactList[i].toString());
}
} catch (Exception e) {}
Contact[] BerlinContactList = new Contact[10] ;
for(int j=0 ; j < 10 ; j++){
BerlinContactList[j] = ShowBerlinsContactList(ContactList)[j] ;
System.out.println(BerlinContactList[j]);
}
}
}
public class Contact {
public String Number;
public String Numerisation;
Contact(String Numerisation, String Number) {
this.Number = Number;
this.Numerisation = Numerisation;
}
public String getNumber() {
return Number;
}
public String getNumerisation() {
return Numerisation;
}
public void setNumber(String number) {
Number = number;
}
public void setNumerisation(String numerisation) {
Numerisation = numerisation;
}
public String toString() {
return Number;
}
}
我尝试将 public static Contact[] ShowBerlinsContactList(Contact[] list) 更改为 public static void 方法,并直接在方法内打印输出并且它可以工作,所以我不明白为什么它不能在数组中返回结果。
【问题讨论】:
-
您正在分配一个充满
null的新空数组,然后立即在其中一个null值上调用方法。 -
不相关:阅读有关 java 命名约定的信息。 camelCase 用于字段和变量。您将字段设为大写的想法......确实具有误导性。不要那样做。
标签: java arrays filter nullpointerexception