How can I create an array of instances accessible in a class? - java

I am writing a code that create an array of instances of Account object in another class (Bank).
I am initializing the array inside the main method, but it is not accessible inside the Bank class.
What I want to do is create 4 instances of the Account class and to be able to perform all tasks inside the Bank class methods. Is there a way that I can do this?
this is my code
Account.java
package question1;
import java.util.Date;
public class Account {
public int AccountNum;
public double BALANCE;
public Date OPENDATE;
public String OwnerName;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(int accnum, double balance, Date opendate, String ownername) {
this.AccountNum = accnum;
this.BALANCE = balance;
this.OPENDATE = opendate;
this.OwnerName = ownername;
}
public int getAccountNum() {
return AccountNum;
}
public void setAccountNum(int accountNum) {
AccountNum = accountNum;
}
public double getBALANCE() {
return BALANCE;
}
public void setBALANCE(double bALANCE) {
BALANCE = bALANCE;
}
public Date getOPENDATE() {
return OPENDATE;
}
public void setOPENDATE(Date oPENDATE) {
OPENDATE = oPENDATE;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String ownerName) {
OwnerName = ownerName;
}
public double yearlyInterest(double balace) {
return balace;
}
}
Bank.java
package question1;
public class Bank {
public static void main(String[] args) {
Account[] acc = new Account[4];
for(int i = 0 ; i<acc.length; i++){
acc[i] = new Account();
System.out.println(acc[i].toString());
}
/// how to continue form here ??
}
}

Call the constructor of the Account class. Now you can set all arguments as desired. Afterwards, you can add the instance to any array or collection.
List<Account> accounts = new ArrayList<Account>(4);
Account myAccount = new Account(123, 100.5, new Date(), "dev leb");
accounts.add(myAccount);

You probably want to have a property of an Account array in your class.
You can set your property in the class body:
public class Bank {
//Set your property here.
private Account[] _acc;
//Initialize in ctor.
public Bank() {
_acc = new Account[4];
}
//....
//You can then use it as a property in your code.
//If needed outside the class, set up setter and getter methods,
//avoiding violating encapsulation.
public Account[] getAcc(){
return _acc;
}
public void setAcc(Account acc){
this._acc = acc;
}
//If you need this to be used inside main, then you must instantiate a
//Bank in main and then make all the appropriate operations there.
public static void main(String[] args) {
Bank bank = new Bank();
Account[] bankAccounts = bank.getAcc();
//....
}
}
My suggestion though is that you use an ArrayList instead:
Set the property:
private List<Account> acc;
And in constructor:
acc = new List();
In order to add an account in a class method:
acc.add(new Account());
In order to retrieve an element by indexing:
acc.get(0);
for more information, look at the ArrayList JavaDoc.
If you are not able to understand why your array that is defined inside the main is not accessible inside your Bank class, then I suggest you search more about Object-Oriented programming, Class definition, instantiation and properties accessibility and manipulation and static methods in Java.

Related

Cannot access method from another java class

I have this Bank class
public class Bank {
public Map<String, Account> accounts;
Bank() {
accounts = new HashMap<>();
}
public void addAccount(String accountType, int accountNumber, double apr) {
accounts.put(accountType, new Account(accountNumber, apr) {
});
}
public Map<String, Account> getAccounts() {
return accounts;
}
}
and I have another class where I am trying to call the addAccount method from the Bank class
public class Processor {
Bank bank = new Bank();
public void openCheckingsAccount(String accType, int accNum, double apr) {
bank.addAccount(accType, accNum, apr);
}
}
I have a JUnit Test class to make sure I can create a new account in the Bank class with the method in my Processor class.
public class ProcessorTest {
Bank bank;
Processor processor;
#BeforeEach
void setUp() {
bank = new Bank();
}
#Test
void create_checkings_and_verify_by_id_apr() {
processor.openCheckingsAccount("checkings", 11111111, 0.6);
System.out.println(bank.accounts);
assertEquals(11111111, bank.getAccounts().get("checkings").getAccountNumber());
}
}
But the result of System.out.println(bank.accounts) is just {} and I get a java.lang.NullPointerException error when running the JUnit test.
Your Processor class has its own instance of a Bank. I guess this is not what you want. That is why when you do bank.getAccounts().get("checkings").getAccountNumber() in your unit test you get a NullPointerException. You are getting the accounts in the bank variable in your test and not the Bank object in your Processor class.
You will need to change your Processor class to receive a Bank object in its constructor as follows:
public class Processor {
private Bank bank;
public Processor(Bank bank) {
this.bank = bank;
}
public void openCheckingsAccount(String accType, int accNum, double apr) {
bank.addAccount(accType, accNum, apr);
}
}
And now also change your test accordingly:
public class ProcessorTest {
Bank bank;
Processor processor;
#BeforeEach
void setUp() {
bank = new Bank();
processor = new Processor(bank);
}
#Test
void create_checkings_and_verify_by_id_apr() {
processor.openCheckingsAccount("checkings", 11111111, 0.6);
System.out.println(bank.getAccounts());
assertEquals(11111111, bank.getAccounts().get("checkings").getAccountNumber());
}
}
Now there is only only Bank instance in your test which is changed by your Processor class.
As a side note, please avoid having public properties in your classes (example: public Map<String, Account> accounts; in your Bank class). They should be private and be accessed via methods in the class. Additionally, keep in mind that when you return the Map in Bank in your getAccounts() method the caller has now a reference to the Map and can change it however he may see fit. Having said that, you should consider returning a new Map (thanks #chrylis-cautiouslyoptimistic- for the hint on the Collections. unmodifiableMap):
public class Bank {
private Map<String, Account> accounts;
public Bank() {
accounts = new HashMap<>();
}
public void addAccount(String accountType, int accountNumber, double apr) {
accounts.put(accountType, new Account(accountNumber, apr) {});
}
public Map<String, Account> getAccounts() {
return Collections.unmodifiableMap(accounts);
}
}

When i am trying to execute getaccountnumber method,getting following error mentioned in the image [duplicate]

This question already has answers here:
method in class cannot be applied to given type
(2 answers)
Closed 2 years ago.
Method getbalance and getaccountnumber are not getting called when i am calling them from the Main class.
public String getaccountnumber(String accountnumber)
{
return accountnumber;
}
public void setaccountnumber(String accountnumber)
{
this.accountnumber = accountnumber;
}
public double getbalance(double balance)
{
return balance;
}
I am getting "method cannot be Applied to given types".
public static void main(String[] args)
{
System.out.println(sanjay.getaccountnumber());
System.out.println(sanjay.getbalance());
As others pointed out in the comments, you need to pass the parameters into the methods, it also looks like you need to create an instance of your class.
Assuming your class with the account methods is like the one below:
public class sanjay
{
public String getaccountnumber(String accountnumber)
{
return accountnumber;
}
public void setaccountnumber(String accountnumber)
{
this.accountnumber = accountnumber;
}
public double getbalance(double balance)
{
return balance;
}
}
You would need to create an instance of the class sanjay as follows:
sanjay mySanjayInstance = new sanjay();
Then you can call the methods with the parameters:
mySanjayInstance.getaccountnumber("myaccountnumber");
mySanjayInstance.setaccountnumber("myaccountnumber");
mySanjayInstance.getbalance(0.4);
As such your main method would look like this:
public static void main(String[] args)
{
sanjay mySanjayInstance = new sanjay();
System.out.println(mySanjayInstance.getaccountnumber("myaccountnumber"));
System.out.println(mySanjayInstance.getbalance(0.4));
}
Taking a guess it seems like you intended to create a class that you set details on, and then retrieve them (with getter and setter methods). As such you would want to use some class variables and remove the parameters from the getter methods.
public class sanjay
{
private String accountnumber;
private double balance;
public String getaccountnumber()
{
return accountnumber;
}
public void setaccountnumber(String accountnumber)
{
this.accountnumber = accountnumber;
}
public double getbalance()
{
return balance;
}
public void setbalance(double balance)
{
this.balance = balance;
}
}
Now your usage would look like this:
public static void main(String[] args)
{
// Create an instance of the `sanjay` class.
sanjay mySanjayInstance = new sanjay();
// Set the properties on the object we just created via the setters.
mySanjayInstance.setaccountnumber("myaccountnumber");
mySanjayInstance.setbalance(0.4);
// Retrieve the properties via the getters.
System.out.println(mySanjayInstance.getaccountnumber());
System.out.println(mySanjayInstance.getbalance());
}
Some observations that can make your life much easier in the long run;
Consider using SnakeCase for class names (so Sanjay instead of sanjay).
And snakeCase for methods and variable names (including parameters), so getAccountNumber instead of getaccountnumber.
public class Account
{
public String getaccountnumber()
{
return accountnumber;
}
public double getbalance()
{
return balance;
}
}
Here is the answer. This will work but it will not help you really understand what you are doing wrong. To really understand the concept of "Classes", "Objects" and "Parameters" I still recommend you follow an introductory tutorial for Java of at least 5 hours.

Trying to get default value from the data definition class

Please consider two classes :
Data Definition Class :
public class A {
private int amount = 1000;
public A(int amount){
this.amount = amount
}
public int getAmount(){
return amount ;
}
}
Main Class :
public class B {
public static void main (String arg[]){
A a = new A(2000);
System.out.println("Amount:"+a.getAmount());
}
}
Since I am passing 2000 to the constructor, I am getting 2000 in the output. But I would like to keep a option of if the user doesn't specifiy any amount, it should print
the default value which is 1000 as mentioned in the private variable in data definition class.
Is there a way I can accomplish my task using the constructor?
public class A {
private int amount;
public A() {
amount = 1000;
}
public A(int amount) {
this.amount = amount;
}
public int getAmount() {
return amount;
}
}
You just need to create an empty constructor
public A(){
}
And in your main you will be able to do this:
A a = new A();
You can provide default constructor along with the one argument constructor you mentioned. This way user don't have to pass the amount if he don't want to while creating the object.
Create an empty constructor
public class A {
private int amount = 1000;
public A(){
}
public A(int amount){
this.amount = amount;
}
public int getAmount(){
return this.amount;
}
}

Returning a String for a Super class' abstract method to display

The abstract method statement (in the super class) must be implemented to return a string representation of a statement.
So I've done the following:
public abstract String statement(); //The abstract method in my super class
..and the method in my subclass:
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
My main class just calls the Account class (the super class in question) as follows:
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]); //ao being the array which contains the values.
However, the console just terminates without displaying anything (I'm also not familiar with implementation).
Here's the full code:
Main:
public class AccountList
{
public static void main(String[] args)
{
int[] ao = {00000,0,0,12345,500,250,23456,230,-50,34567,340,500,45678,-320,-50,56789,-320,-500};
for(int i=0;i<ao.length;i=i+3)
{
int a = i+2;
if(ao[a]>=0)
{
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
if(ao[a]<=0)
{
new ChequeAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
}
}
}
}
Super class:
public abstract class Account implements InterestAccount
{
static String accountNumber;
int balance;
public Account()
{
accountNumber = "00000";
balance = 0;
//statement();
}
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
public void setAccountNum(String accNum)
{
accountNumber = accNum;
}
public void setBalance(int balance)
{
this.balance = balance;
}
public String getAccountNumber()
{
return accountNumber;
}
public int getBalance()
{
return balance;
}
public abstract String statement();
}
One of the sub-classes:
public class SavingsAccount extends Account
{
int minBalance;
public SavingsAccount()
{
super();
minBalance = 0;
}
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
public int getMinBalance()
{
return minBalance;
}
#Override
public int calculateInterest(int value) {
if(minBalance>balance)
{
return 0;
}
else
{
return (minBalance*balance)/100;
}
}
//#Override
public String statement()
{
return String.format("Account no %d has balance R%d and minimum balance R%d", accountNumber,balance,getMinBalance());
}
}
You never calls the method statement.
1) create a new SavingsAccount object
new SavingsAccount(Integer.toString(ao[i]),ao[i+1],ao[a]);
2) Constructor class got call by above statement
public SavingsAccount(String accountNum,int minBalance,int balance)
{
super(accountNum,balance);
setMinBalance(minBalance);
}
3) Subclass then call superclass method
public Account(String accountNumber,int balance)
{
setAccountNum(accountNumber);
setBalance(balance);
}
4) SetBalance is called
public void setBalance(int balance)
{
this.balance = balance;
}
5) setMinBalance called
public void setMinBalance(int minBalance)
{
this.minBalance = minBalance;
}
6) End of create object SavingsAccount
No single statement calling the method statement
It might help to know more of your code, but from what I see, there are some possible cases:
Your code runs and terminates without an error. Reason you don't see anything is, there is nothing written to the standard output stream (e.g. via System.out.println()).
Your code has some internal problems, which cause an exception, which again is not shown due to a broken logging mechanism.
In any case, use a debugger to step through you code and determine which parts run perfectly and if any fail. It might help to extract some local variables, give them proper meaningful names and watch their contents during execution.

New use in Java (Can someone tell me why this is not working like i keep getting errors)

Can someone tell me where this is not working? Particularly the usage of the new keyword in the two methods.
import java.util.Scanner;
public class dotPractice {
public static void main (String args[]) {
BankAccount b1 = new BankAccount("Ade", 500.00);
}
public static void BankAccount(String Password, double balance) {
// so i created a method for a bank account
Scanner input = new Scanner(System.in);
String Password = input.nextLine();
balance = input.nextDouble();
}
}
You seem to have defined BankAccount as a static method of the dotPractice class, when instead I think you want to define BankAccount as a class itself:
public class BankAccount
{
public BankAccount(String password, double balance)
{
//
}
}
public class dotPractice
{
public static void main(String[] args)
{
BankAccount b1 = new BankAccount("Ade", 500.00);
}
}
The BankAccount should be a class not a static method.
import java.util.Scanner;
public class DotPractice {
public static void main (String args[]) {
BankAccount b1=new BankAccount("Ade", 500.00);
}
public class BankAccount {
public BankAccount(String Password, double balance) {
//so i created a method for a bank account
Scanner input= new Scanner(System.in);
String Password=input.nextLine();
balance=input.nextDouble();
}
}
}
You can't create a new methode (new BankAccount)
You need to create a new class (new .java file) called BankAccount with a constructor
public class BankAccount {
public BankAccount(String password, double balance){
Scanner input= new Scanner(System.in);
String Password=input.nextLine();
balance=input.nextDouble();
}
}
than you can call from your main
BankAccount b1=new BankAccount("Ade", 500.00);
If you want to create a new object with the values u give it in the new BankAccount("Ade", 500.00);
the code should be this
public class BankAccount {
private String password;
private double balance;
public BankAccount(String password, double balance){
this.password = password;
this.balance = balance;
}
}
What this does, is store the give string and balance in variables which are privates to this class (bank account object) and only it can access it
you can set it to public and then u could write in the main
b1.balance and get the balance, but it's bad programming style.

Categories

Resources