user3375421
user3375421

Reputation: 29

Exception in thread "main" java.lang.NullPointerException Read element from txt

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");
        }
   }
}

Upvotes: 0

Views: 81

Answers (1)

nikis
nikis

Reputation: 11234

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.

Upvotes: 2

Related Questions