Results 1 to 8 of 8
  1. #1
    GrantM is offline Member
    Join Date
    May 2012
    Posts
    3
    Rep Power
    0

    Default Exception in thread "main" java.lang.NullPointerException

    I am new to Java and have read numerous forums about this error but still can't see what's wrong. I am only showing the relevant classes. There are a few more but are unrelated to this error.

    Java Code:
    /**
     * @(#)ATMsystem.java
     *
     * ATMsystem application
     *
     * @author
     * @version 1.00 2012/5/14
     */
    
    public class ATMsystem {
    
        public static void main(String[] args) {
    
        	// TODO, add your application code
        	ATM atmSystem = new ATM();
        	atmSystem.run();
        }
    }
    Java Code:
    public class ATM {
    
    	private boolean userAuthenticated;
    	private int currentAccountNumber;
    	private BankDatabase bankDatabase;
    	private Screen screen;
    	private Keypad keypad;
    
    	private static final int BALANCE_ENQUIRY = 1;
    	private static final int WITHDRAWAL = 2;
    	private static final int DEPOSIT = 3;
    	private static final int EXIT = 4;
    
    	public ATM()
    	{
    
    		userAuthenticated = false;
    		currentAccountNumber = 0;
    		screen = new Screen();
    		keypad = new Keypad();
    		bankDatabase = new BankDatabase();
    
    	}
    
    
    	public void run()
    	{
    
    		while(true)
    		{
    
    			while(!userAuthenticated)
    			{
    				System.out.println("Welcome to Grant's Bank!");
    
    				authenticateUser();
    
    
    			}
    
    
    			//performTransactions();
    
    			System.out.println("Thank you! Goodbye!");
    
    		}
    
    
    
    
    	}
    
    
    	public void authenticateUser()
    	{
    
    		System.out.println("Please enter you Account Number:");
    		int accountNumber = keypad.getInput();
    
    		System.out.println("Please enter you Pin Number:");
    		int pin = keypad.getInput();
    
    		userAuthenticated = bankDatabase.authenticateUser (accountNumber, pin);
    
    		if (userAuthenticated)
    		{
    			System.out.println("Authenticated");
    
    		int accountNumber2 = keypad.getInput();
    		}
    		else
    		{
    			System.out.println("Authenticated not authenticated");
    
    		int accountNumber3 = keypad.getInput();
    		}
    
    
    
    
    	}
    
    
    
    }
    Java Code:
    public class BankDatabase {
    
    
    	private Account[] accounts;
    
    
    	public BankDatabase()
    	{
    
    	Account accounts[] = new Account[2];
    
    	accounts[0] = new Account (4074, 2304, 6000.00, 6000.00);
    	accounts[1] = new Account (4073, 4628, 6000.00, 6000.00);
    
    	}
    
    	private Account getAccount(int accountNumber)
    	{
    
    		for (Account currentAccount : accounts)
    		{
    			if (currentAccount.getAccountNumber() == accountNumber)
    				return currentAccount;
    
    		}
    
    
    	return null;
    	}
    
    
    
    
    	public boolean authenticateUser(int userAccountNumber, int Pin)
    	{
    
    		Account userAccount  = getAccount(userAccountNumber);
    
    
    		if (userAccount != null)
    		{
    		return userAccount.validatePin(Pin);
    		}
    		else
    		return false;
    	}
    
    
    
    
    
    
    
    
    }
    Java Code:
    public class Account {
    
    
    	private int accountNumber;
    	private int Pin;
    	private double availableBalance;
    	private double totalBalance;
    
    
    	public Account(int theAccountNumber, int thePin, double theAvailableBalance, double theTotalBalance)
    	{
    
    		accountNumber = theAccountNumber;
    		Pin = thePin;
    		availableBalance = theAvailableBalance;
    		totalBalance = theTotalBalance;
    
    	}
    
    
    
    
    
    
    	public int getAccountNumber()
    	{
    	return accountNumber;
    	}
    
    	public double getAvailableBalance()
    	{
    	return availableBalance;
    	}
    
    	public double getTotalBalance()
    	{
    	return totalBalance;
    	}
    
    	public boolean validatePin(int pin)
    	{
    
    		if(Pin == pin)
    		   return true;
    		else
    		   return false;
    
    	}
    
    }
    Java Code:
    import java.util.Scanner;
    
    
    
    public class Keypad {
    
    	private Scanner input;
    
    
    	public Keypad()
    	{
    		input = new Scanner(System.in);
    	}
    
    
    	public int getInput()
    	{
    
    		return input.nextInt();
    	}
    }





    I get the following error:
    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at BankDatabase.getAccount(BankDatabase.java:21)
    	at BankDatabase.authenticateUser(BankDatabase.java:38)
    	at ATM.authenticateUser(ATM.java:67)
    	at ATM.run(ATM.java:40)
    	at ATMsystem.main(ATMsystem.java:16)

    I have been over this a million times and just can't find the issue. I seriously need help urgently...writing an exam soon!

    Thanks guys :)
    Last edited by pbrockway2; 05-17-2012 at 10:37 PM. Reason: code tags added

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: Exception in thread "main" java.lang.NullPointerException

    Please wrap your code in the code tags - it is practically unreadable. And just a head up for future reference - every post here is urgent for those posting their questions - demonstrating this in any way (for instance mentioning your urgency) can be construed as rude to those other people and the members who are trying to answer them all in turn.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Exception in thread "main" java.lang.NullPointerException

    Hi GrantM, welcome to the forums!

    When you post code it's a good idea to use the "code" tags: put [code] at the start of the code and [/code] at the end. This will preserve formatting and make the code more readable.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Exception in thread "main" java.lang.NullPointerException

    Quote Originally Posted by GrantM View Post
    I get the following error:
    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at BankDatabase.getAccount(BankDatabase.java:21)
    	at BankDatabase.authenticateUser(BankDatabase.java:38)
    	at ATM.authenticateUser(ATM.java:67)
    	at ATM.run(ATM.java:40)
    	at ATMsystem.main(ATMsystem.java:16)
    You read these stack traces from the top down looking especially at the first line that refers to your code. (the very first in this case). This is where the exception "happened" from your point of view with the following lines describing the context.

    Evidently the error exception occurred on line 21 of BankDatabase.java in the getAccount() method.

    "NullPointerException" has a very precise meaning: you used a variable (or other expression) as if it had a non null value when it was really null. Common examples are saying "foo.bar()" when foo is null, or "foo[bar]".

    Line 21 would appear to be this one:

    Java Code:
    for (Account currentAccount : accounts)
    That's good because if what I said about the NPE has any validity, the culprit would appear to be accounts. Check that. I mean check that what I said suggests to you that accounts is the problem - or at any rate deserves closer inspection.

    Then use System.out.println() to see what's going on by printing the value of accounts.

    Java Code:
    private Account getAccount(int accountNumber)
    {
        System.out.println("About to start loop, accounts=" + accounts); 
        for (Account currentAccount : accounts)
        {
            if (currentAccount.getAccountNumber() == accountNumber)
                return currentAccount;
     
        }
     
     
            return null;
    }
    If it turns out that accounts is null your next step will be to see why. More precisely, go back through your code to where you thought you had assigned this variable a non null value and figure out why that didn't happen.
    Last edited by pbrockway2; 05-17-2012 at 11:02 PM.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Exception in thread "main" java.lang.NullPointerException

    Sorry - made too many mistakes in my previous post. (Just started the day, and need more coffee). All corrected now. I hope.

  6. #6
    GrantM is offline Member
    Join Date
    May 2012
    Posts
    3
    Rep Power
    0

    Default Re: Exception in thread "main" java.lang.NullPointerException

    I am not sure why accounts is null because my constructor initialized it to values. I assume there is an issue with the way i initialized them in the constructors? But this could is pretty much taken straight out of a textbook and can't see any difference between the code.

  7. #7
    GrantM is offline Member
    Join Date
    May 2012
    Posts
    3
    Rep Power
    0

    Default Re: Exception in thread "main" java.lang.NullPointerException

    I think i found the problem. My accounts object was initialized incorrectly. Line 10 of BankDatabase should be:

    accounts = new Account[2];

    Is this correct?

  8. #8
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Exception in thread "main" java.lang.NullPointerException

    Yes, exactly.

    The best confirmation comes from compilng and running, but you are quite right. As you had it before you declared a new variable in the constructor which is said to hide or mask the class's instance variable. You initialised this new variable but left the other one (which you later wanted to use) as null.

    It's a common misake! But once seen and understood you grow to avoid it by being conscious of what instance variables you have declared and, when you declare them, thinking "where will this get intialised?", "when (if ever) will this value get changed?".

Similar Threads

  1. Replies: 6
    Last Post: 04-19-2012, 07:10 PM
  2. Replies: 5
    Last Post: 12-21-2011, 06:44 PM
  3. Replies: 5
    Last Post: 10-11-2011, 12:16 AM
  4. Replies: 6
    Last Post: 07-16-2009, 03:30 PM
  5. Replies: 1
    Last Post: 07-16-2009, 10:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •