0

I am a beginner in java programming. I am trying to develop a program but when I ran my program which is posted below and it came back with this error:

Exception in thread "main" java.lang.NullPointerException
    at ChargeAccount1.isValid(ChargeAccount1.java:39)
    at ChargeAccount1Test.main(ChargeAccount1Test.java:22)

Here is my code:

import java.io.*;
import java.util.*;

public class ChargeAccount1 {

 private  int [] valid;

    public void main(String[] args) throws IOException {
         FileReader file = new FileReader("Account.txt");

        valid=new int [10];
        int i=1;

            Scanner input = new Scanner(file);
            while(input.hasNext())
            {
                valid[i] = input.nextInt();
                i++;
            }
            input.close();

        }


    public boolean isValid(int number) {
        boolean found = false;
        int n = 0;
        while (!found && n < valid.length) {
            if (valid[n] == number) {
                found = true;
            } else {
                n++;
            }
        }
        return found;
    }
}
public class ChargeAccount1Test {
   public static void main(String[]args)throws IOException{
        ChargeAccount1 in = new ChargeAccount1();
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a charge account number:");
        String account = scan.nextLine();
        int number = Integer.parseInt(account);
        if (in.isValid(number)) {
            System.out.println("This is a valid account number");
        } else {
            System.out.println("This is an invalid account number");
        }
   }
}
2
  • would you please mark the line with the exception, we don't have line numbers... Commented Mar 3, 2014 at 15:17
  • Don't expect the main of ChargeAccount1 to be executed, since not the root of the program. Indeed, ChargeAccount1Test is the root. Commented Mar 3, 2014 at 15:18

1 Answer 1

2

Your valid is null. main method is not a constructor, it's just an top-level entry point point. So when you make a call in.isValid(number), valid inside your object is null since you initialize it only at the main method and that's why you may want to call in.main(null) at first.

Sign up to request clarification or add additional context in comments.

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.