I have created a class, and the object of it is to compare account numbers to an array of account numbers and call a method to return whether a number is valid. I am receiving a compiler error of : Exception in thread "main" java.lang.NullPointerException at program07.AccountVal.(AccountVal.java:12) at program07.Program07.main(Program07.java:18)
我创建了一个类,它的对象是将帐号与帐号数组进行比较,并调用一个方法来返回一个数字是否有效。我收到编译器错误:在program07.AccountVal的线程“main”java.lang.NullPointerException中的异常。(AccountVal.java:12)在program07.Program07.main(Program07.java:18)
Here is my class
这是我的课
package program07;
public class AccountVal
{
private String[] accountNums;
private String newAccount;
public AccountVal()
{
accountNums[0] = "5658845";
accountNums[1] = "8080152";
accountNums[2] = "1005231";
accountNums[3] = "4520125";
accountNums[4] = "4562555";
accountNums[5] = "6545231";
accountNums[6] = "7895122";
accountNums[7] = "5552012";
accountNums[8] = "3852085";
accountNums[9] = "8777541";
accountNums[10] = "5050552";
accountNums[11] = "7576651";
accountNums[12] = "8451277";
accountNums[13] = "7825877";
accountNums[14] = "7881200";
accountNums[15] = "1302850";
accountNums[16] = "1250255";
accountNums[17] = "4581002";
newAccount = "";
}
public void setAccountNums(String[] acc)
{
accountNums = acc;
}
public void setNewAccount(String newAcc)
{
newAccount = newAcc;
}
public String[] getAccountNums()
{
return accountNums;
}
public String getNewAccount()
{
return newAccount;
}
public boolean AccountValidation(String newAccount)
{
boolean test = false;
for (int i = 0; i < 18; i++)
{
if(newAccount == accountNums[i])
{
test = true;
}
}
return test;
}
}
The line the error refers to from the program is when i declare the object:
错误从程序引用的行是当我声明对象时:
AccountVal test = new AccountVal();
any help would be greatly appreciated. Thank You!
任何帮助将不胜感激。谢谢!
2 个解决方案
#1
2
The NPE
is occurring on this line
NPE正在这条线上发生
accountNums[0] = "5658845";
as the String
array accountNums
has not been initialized. You could do:
作为String数组,accountNums尚未初始化。你可以这样做:
private String[] accountNums = new String[18];
Alternatively, rather than using an array size & using indices, you could declare your array:
或者,您可以声明您的数组,而不是使用数组大小和使用索引:
private String[] accountNums = { "5658845", "8080152", ... };
#2
0
You never initialize the accountNums
array. You will need to say:
您永远不会初始化accountNums数组。你需要说:
private String[] accountNums = new String[18];
#1
2
The NPE
is occurring on this line
NPE正在这条线上发生
accountNums[0] = "5658845";
as the String
array accountNums
has not been initialized. You could do:
作为String数组,accountNums尚未初始化。你可以这样做:
private String[] accountNums = new String[18];
Alternatively, rather than using an array size & using indices, you could declare your array:
或者,您可以声明您的数组,而不是使用数组大小和使用索引:
private String[] accountNums = { "5658845", "8080152", ... };
#2
0
You never initialize the accountNums
array. You will need to say:
您永远不会初始化accountNums数组。你需要说:
private String[] accountNums = new String[18];