I just started learning java and I’m trying to figure out the following requirement. I want to create a instances of my own class as an array. Then I want to refer each object using a loop and enter data. My class is "BankAccount". My instances are "acct[]". But when I try to insert data in to instances I get the following error. Can some one help me to identify the problem.
My code is as follows;
public class BankAccount {
private String accNo;
private String name;
private String type;
private double balance;
//Constructor
public void BankAccount(String accNo, String name, String type, double balance) {
this.accNo = accNo;
this.name = name;
this.type = type;
this.balance = balance;
}
//Diposit
public void diposit(double amount) {
balance += amount;
}
//Withdraw
public void withdraw(double amount) {
if (amount < balance)
balance -= amount;
else
System.out.println("Balnce not enough for the withdrawal");
}
//Display data
public void display() {
System.out.println("Acc No" + this.accNo);
System.out.println("Name : " + this.name);
System.out.println("Type : " + this.balance);
System.out.println("balance : " + this.balance);
System.out.println("-------------------------------------------------------------------");
}
}
public class testBankAccount {
public static void main(String[] args) {
//Declaring 10 BankAccount objects as an array
BankAccount[] acct = new BankAccount[10];
//inserting data to each object using a loop
for (int i = 1; i < 11; i++) {
acct[i].BankAccount("Acc", "name", "type", 0);
acct[i].diposit(1000);
acct[i].withdraw(500);
acct[i].display();
}
}
}
>Solution :
You need to create the object, before you can work with it. BankAccount[] acct = new BankAccount[10]; creates the array, it does not create object in every position in the array. You need to create the object before you can invoke its’ methods.
acct[i] = new BankAccount();
Other things to note:
public void BankAccountis not a constructor, you have declared a method. Constructor looks like this
public BankAccount(String accNo, String name, String type, double balance) {
//set fields
}
- Arrays indexes are zero based, meaning
for (int i=1; i<11; i++)will skip first element and throw exception on the last iteration. Correct would be
for (int i=0; i<10; i++) {
//do stuff
}
- You really should format your code properly(best to follow java conventions), you will make your own life easier when developing.
