My program outputs a null when I'm trying to enter an amount in deposit, withdraw, balance inquiry, and account information when I try to select I already have an account but runs smoothly if I shoose to create a new account.
public class BankAtm {
public static SavingsAccount accnt;
public static void main(String[] args) {
JTextField name = new JTextField();
JTextField pin = new JTextField();
JTextField aage = new JTextField();
JTextField contactNo = new JTextField();
String aNo;
String aName;
String aPin;
int age;
String aContactNo;
String[] choices = {"Yes", "I already have an account", "Exit"};
int y = JOptionPane.showOptionDialog(null, "Would you like to open a new acount?" ,
"Bank ATM",
JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, choices, choices[0]);
switch (y) {
case 0:
int max = 500;
int min = 100;
Object[] a = {"Account Name: ", name, "Age: ", aage, "Account Pin Number: ", pin, "Contact Number (please input parent's or guardian's contact number if below 18): ", contactNo};
JOptionPane op= new JOptionPane(a, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null);
JDialog dialog= op.createDialog(null, "Create New Account");
dialog.setVisible(true);
aName = name.getText();
age = Integer.parseInt(aage.getText());
aPin = pin.getText();
aContactNo=contactNo.getText();
int no = (int) (Math.random()*(max-min+1)+max);
JOptionPane.showMessageDialog(null, "Your account number is "+no);
aNo = Integer.toString(no);
accnt = new SavingsAccount (aName, aNo, aPin);
accnt.accntName=aName;
accnt.accntNo= aNo;
accnt.accntAge= age;
accnt.accntPin= aPin;
accnt.accntContactNo=aContactNo;
case 1:
int trans;
String php;
double amt;
do {
String s = JOptionPane.showInputDialog("1. Deposit"
+ "\n2. Withdraw"
+ "\n3. Balance Inquiry"
+ "\n4. Display Account Info"
+ "\n5. Exit");
trans = Integer.parseInt(s);
switch (trans) {
case 1:
php = JOptionPane.showInputDialog("Enter amount to deposit: ");
amt = Double.parseDouble(php);
accnt.deposit(amt);
break;
case 2:
php = JOptionPane.showInputDialog("Enter amount to withdraw: ");
amt = Double.parseDouble(php);
accnt.withdraw(amt);
break;
case 3:
accnt.balInquiry();
break;
case 4:
accnt.displayAccntInfo();
break;
case 5:
JOptionPane.showMessageDialog(null, "Thank you for using our service!~");
break;
}
} while (trans!=5);
}
return;
}
}
The program outputs Exception in thread "main" java.lang.NullPointerException: Cannot invoke "SavingsAccount.displayAccntInfo()" because "BankAtm.accnt" is null
In the case 0 of your
switch, you're creating a newSavingsAccountthrough its constructor, thus giving him a value, but if you enter case 1 of thatswitch, the account constructor is never called since you just declare it so:When you initialise a variable without assigning it a value, it gets a default value, which is
null. You cannot access the properties of anullobject, since it doesn't have any. You have to call the constructor from somewhere before using any method on your object.