0

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)

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 Answers 2

2

The NPE is occurring on this line

accountNums[0] = "5658845";

as the String array accountNums has not been initialized. You could do:

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", ... };
Sign up to request clarification or add additional context in comments.

Comments

0

You never initialize the accountNums array. You will need to say:

private String[] accountNums = new String[18];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.