Java getter setter failing to store value - java

I'm trying to answer these questions.
The New Account option should implement the following:
Input client details: name, address, birthday, and contact number
Input the initial deposit of not less than PhP5,000
Generate a four-digit account number randomly
The Balance Inquiry option should implement the following:
Input the account number and validate
If the account number is valid, display the client name and current
balance
I've tried coding the New Account option with setter methods in it and also generates a four-digit number randomly that I can use to input it in the Balance Inquiry option that has getter methods but it displays empty. I tried debugging it and the variables return empty after exiting the if statement.
Class with the main method, displayMainMenu() for the options, newAccount() and fourRandomNumber().
public class ClientUgang {
public static void main(String[] args) {
displayMainMenu();
}
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
int option = 0;
while (option != 7) {
Scanner scan = new Scanner(System.in);
System.out.println("JBank Main Menu");
System.out.println("[1] New Account");
System.out.println("[2] Balance Inquiry");
System.out.println("[3] Deposit");
System.out.println("[4] Withdraw");
System.out.println("[5] Client Profile");
System.out.println("[6] Close Account");
System.out.println("[7] Exit");
option = scan.nextInt();
if (option == 1) {
newAccount();
}
if (option == 2) {
savingsAccount.balanceInquiry();
}
}
}
public static void newAccount() {
Scanner scan = new Scanner(System.in);
SavingsAccountUgang savingsAccount = new SavingsAccountUgang();
System.out.print("Name: ");
String name = scan.nextLine();
System.out.print("Address: ");
String address = scan.nextLine();
System.out.print("Birthday: ");
String birthday = scan.nextLine();
System.out.print("Contact number: ");
String contactNumber = scan.nextLine();
savingsAccount.setAccountName(name);
savingsAccount.setAddress(address);
savingsAccount.setBirthday(birthday);
savingsAccount.setContactNumber(contactNumber);
int deposit = 0;
while (deposit < 5000) {
System.out.print("Initial deposit(not less than Php5000): ");
deposit = scan.nextInt();
}
savingsAccount.setBalance(deposit);
int fourDigitNumber = fourRandomNumber(1000, 9000);
savingsAccount.setAccountNo(fourDigitNumber);
System.out.println("Your Account Number: " + fourDigitNumber);
System.out.println();
}
public static int fourRandomNumber(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
The Class where my balanceInquiry() method is. My setter and getter method for accountName is in BankAccountUgang class.
public class SavingsAccountUgang extends BankAccountUgang {
private int accountNo;
private double balance;
public SavingsAccountUgang() {
}
public int getAccountNo() {
return accountNo;
}
public void setAccountNo(int accountNo) {
this.accountNo = accountNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void balanceInquiry() {
Scanner scan = new Scanner(System.in);
int accountNumber = 0;
do {
System.out.print("Enter Account Number: ");
accountNumber = scan.nextInt());
} while (accountNumber != getAccountNo());
System.out.println(getAccountName());
System.out.println(getBalance());
System.out.println();
}
}
I expect the setter methods to work so that I can call the getter methods.
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
1
Name: John
Address: World
Birthday: Aug 2019
Contact number: 123 1234
Initial deposit(not less than Php5000): 5000
Your Account Number: 6810
JBank Main Menu
[1] New Account
[2] Balance Inquiry
[3] Deposit
[4] Withdraw
[5] Client Profile
[6] Close Account
[7] Exit
2
Enter Account Number: 6810
Enter Account Number: BUILD STOPPED (total time: 27 seconds)

There are a lot of issues with your code.
To fix that 1 way is below:
Return a new saving account from the newAccount method, so change the return type to:
public static SavingsAccountUgang newAccount() {
// Your existing code
return savingsAccount;
}
Then in your displayMainMenu() method save this account if the user enters 1 as an input and later use that instance to show the balance:
public static void displayMainMenu() {
SavingsAccountUgang savingsAccount = null // don't create object here as you are doing
// Your code
if (option == 1) {
savingsAccount = newAccount();
}
if (option == 2) {
if(savingsAccount == null) {
// throw exception or whatever you want to do.
}
savingsAccount.balanceInquiry();
}
}

The SavingsAccountUgang instance in your newAccount() method is a local variable and therefore only visible to this method.
If you want to use it outside your method you have to return or declare it outside of your method.

Well, the setBalance() method requires an argument type double, but you send a type int, but it's not a reason for a mistake. Also, you should use this in a statement like this one:
while (accountNumber != this.getAccountNo());

Related

How to create multiple accounts with user input using class constructor

I have created this bank account class constructor in java that makes it possible to create any number of accounts. This is part of an assignment for my java course. However, I have to manually specify each attribute of the accounts (Account ID, and balance).
What I want to do is get the user involved. For example, the user should be prompted if they want to create a new account. If they answer yes, they should be able to set the account number (weird? I know) and the account balance. The program should then create the account for them using the inputs.
I already have the options for checking account balance, making deposit or withdrawal that is working as expected, however, I want it to work for multiple accounts created. For example, the user is prompted if they want to create new account, and if yes, specify account number and balance. If they want to check the status of existing accounts, the program should give them an option of which account they want to get info about. Then the program should go through the routine behavior of displaying the prompts that I have already created.
It would also be nice if the code lets the user to create multiple accounts at once. For example:
In main, create an array of 10 Account objects with id 0 - 9 and starting balance of $100 each.
Prompt the user for an id.
Prompt the user for an amount to withdraw or deposit (or both).
Modify that Account, then print its balance.
Here is my existing class constructor portion:
// Bank account class creator
public class Account {
// Create attributes for the Account class
private int id;
private double balance;
private double withdraw;
private double deposit;
private static double annualRate;
private static String dateCreated;
// Create default constructor
Account() {
id = 0;
balance = 0;
java.util.Date date = new java.util.Date();
dateCreated = date.toString();
annualRate = 4.5;
}
// Create constructor which allows input values
Account(int accountId, double accountBalance) {
this.id = accountId;
this.balance = accountBalance;
}
// Getter for account ID
int getId() {
return this.id;
}
// Getter for account balance
double getBalance() {
return this.balance;
}
// Getter for annual interest rate
double getAnnualRate() {
return this.annualRate;
}
// Getter for date
String getDate() {
return this.dateCreated;
}
// Getter for monthly interest amount
double getMonthlyInterest() {
return this.balance * this.annualRate / 1200;
}
// Getter for annual interest amount
double getAnnualInterest() {
return this.balance * this.annualRate / 100;
}
// Validate deposit (filter negative numbers out)
double deposit(double depositAmount) {
if (depositAmount > 0) {
this.balance = this.balance + depositAmount;
return this.balance;
}
else return 0;
}
// Validate withdraw (filter negative numbers out)
double withdraw(double withdrawAmount) {
if (withdrawAmount > 0) {
this.balance = this.balance - withdrawAmount;
return this.balance;
}
else return 0;
}
// Validate ID (filter negative numbers out)
void setId(int accountId) {
if (accountId > 0)
this.id = accountId;
else
this.id = 0;
}
// Validate interest rate (filter negative numbers out)
void setAnnualRate(double currentInterest) {
if (currentInterest > 0)
this.annualRate = currentInterest;
else
this.annualRate = 0;
}
// Setter for balance
void setBalance() {
this.balance = this.balance + this.deposit - this.withdraw;
}
}
Here is the main code that uses the constructor to create accounts:
// Bank account tester
import java.util.Scanner; // import java Scanner utility
public class TestAccount {
public static void main(String[] args) {
Account account1 = new Account(); // Create a new account
Scanner input = new Scanner(System.in); // Create a Scanner object
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
System.out.println("");
System.out.print("Enter choice: ");
int userInput = input.nextInt(); // Get input from the user
while (userInput != 4) { // Start of loop to check for exit condition
if(userInput == 1) {
// Display account balance, monthly interest and current date
System.out.printf("Balance: $%.2f\n" , account1.getBalance());
System.out.printf("Monthly interest $%.2f\n" , account1.getMonthlyInterest());
System.out.println("Date created: " + account1.getDate());
}
else if (userInput == 2) {
// Deposit funds to account
System.out.println("Enter amount to deposit:");
double inputAmount = input.nextDouble();
account1.deposit(inputAmount);
}
else if (userInput == 3) {
// Withdraw funds from account
System.out.println("Enter amount to withdraw:");
double inputAmount = input.nextDouble();
account1.withdraw(inputAmount);
} else
// Prompt the user to input option choice if they input invalid option
System.out.println("That is not a valid choice. Please enter a valid choice; ");
// Continue displaying the options until the user's option is to exit
System.out.println("");
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
userInput = input.nextInt(); // Continue getting inputs until user chooses to exit
}
input.close(); // close the input method
// Display an exit message when the user chooses to exit
System.out.println("Thank you for using our banking software ");
}
}
I would also appreciate if you could point out to any error or redundancy in my code, for example incorrect use of static or redundant "this." keyword.
Few thing regarding of possible refactoring:
Invalid use of static in Account:
the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
Blockquote
annualRate and dateCreated should NOT be static as it means that these values will be shared among all instances of Account class.
Its possible to remove duplicated code for print of program options:
private void printHelp() {
System.out.println("1. Show balance");
System.out.println("2. Deposit funds");
System.out.println("3. Withdraw funds");
System.out.println("4. Exit");
}

JOptionPane not displaying and code doesn't proceed

I have been trying to build a simple java application which simulates bank deposits and withdrawals.
I tried to use the JOptionPane to show an error if the user tries to withdraw more than the bank account balance. But the JOptionPane does not display the message and the code does not proceed to the next line.
My Bank class which contains the main application
import java.util.Scanner;
public class Bank {
public static void main(String[] args)
{
//Define an object of type Scanner to get the input
Scanner inp = new Scanner(System.in);
String name; //Local variable to get the name
double bal; //Local variable to get the balance
//Getting the inputs from the user
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a1 = new Account(name, bal); //Creating Account object a1
inp.nextLine();
/**The above command is to remove the newline character after
inp.nextDouble() since it is not consumed by it and this affects
the string input in the following lines*/
System.out.println("Enter the name: ");
name = inp.nextLine();
System.out.println("Enter the balance: ");
bal = inp.nextDouble();
Account a2 = new Account(name, bal); //Creating Account object a2
//Displaying the input details
a1.dispDetails();
a2.dispDetails();
/**For this app we just withdraw money from a1 and deposit in a2 */
System.out.println("Enter the amount to be withdrawn from a1");
double w_d = inp.nextDouble();
a1.withdraw(w_d);
a1.dispDetails();
System.out.println("Enter the amount to be deposited in a2: ");
double deposit = inp.nextDouble();
a2.credit(deposit);
a2.dispDetails();
System.out.println( "Number of accounts created is "+Account.getCount());
}
}
My Account class in which the JOptionPane is not working
import javax.swing.*;
public class Account {
/** Declaration of the class variables*/
private final String name; //store the name of the account holder
private double balance;//store the balance
private final int acc_num; //since account number is not changed, set as final
static int count = 0; //to keep track of the number of accounts
JFrame f = new JFrame();
public Account(String n,double bal)
{
count++;
this.name = n;
//generating a random account number based on count
this.acc_num = count*599*254715;
this.balance = bal;
}
/** static function to access the static variable*/
static int getCount()
{
return count;
}
/** To deduct amount on withdrawal Raises a warning if there is
insufficient balance*/
public void withdraw (double amt)
{
if(amt < balance)
balance -= amt;
else
{
JOptionPane.showMessageDialog(f, "Insufficient Balance");//not working
}
}
//credit an amount to the account
public void credit (double amt)
{
balance += amt;
}
//display the details of the account
public void dispDetails()
{
System.out.println("Name: "+name+"\nAccount number: "+acc_num);
System.out.println("Balance= "+balance+"\n");
}
}
It does not get any input or stop running after the JOptionPane line.
Please help. Thanks
I think it has something to do with the AWT-Thread and how the shutdown happens (it needs at least one active window it seems). I fixed it by creating an invisible JFrame which somehow doesn't let the AWT-Threads end. Just put this as the first statements in your main:
JFrame f = new JFrame();
f.setVisible(true);
SwingUtilities.invokeLater(() -> f.setVisible(false));
and your JOptionPane will work.

How to make ArrayList or other to work for finding a specific data in the stored list

I have written a code that takes input as Account details and displays the details by using ArrayList. I however want the list to fetch a particular/specific account details only for a data. Lets say i stored account number details for 127783 and 127784. Now i want only account number 127783 details. How do i fetch that using arrayList. If it doesn't happen with an ArrayList then what to use.
package com.techlabs.account;
import java.util.ArrayList;
import java.util.Scanner;
public class AccountMenu {
static int accountno;
String name;
double balance;
ArrayList a = new ArrayList();
public AccountMenu() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
if (number == 1) {
System.out.println("Enter the Account no.");
accountno = in.nextInt();
a.add(accountno);
System.out.println("Enter the name");
name = in.next();
a.add(name);
System.out.println("Enter the Balance");
balance = in.nextDouble();
a.add(balance);
}
if (number == 2) {
System.out.println("Account details are :");
for (Object b : a) {
System.out.println(b);
}
}
if (number == 3) {
System.out.println("Enter the account number");
accountno=in.nextInt();
if (a.contains(accountno)) {
System.out.println(a);
}
}
if (number == 4) {
System.out.println("Exit");
}
System.out.println("Enter the option :1. Open Account 2. Show Account details 3.Retrieve details by Searching Account Number and 4. Exit again");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu am = new AccountMenu();
}
}
Instead of dropping everything into a list of objects I would create a class for storing account details (with members of account number, name, balance).
I would store these in a Map < Integer, Account >. When you need a specific account's detail you can say map.get(accountNumber) and you will get back your specific Account instance.
Edit:
A wrapper class to hold Account details:
public Class AccountDetails{
public final int accountNumber;
public final String name;
public final int balance;
constructor
}
Instead of arraylist a should be:
Map<Integer, AccountDetails> a = new HashMap<>();
Where your create new accounts:
AccountDetails accountDetails = new AccountDetails(accountno, name, balance);
a.put(accountno, accountDetails)
Where you print details you should ask for the account number from the user, and after that:
System.out.println(a.get(accountno));
Of course to see something meaningful you should write a toString() method for the AccountDetails class.
I found a lot of errors relatying to POO in your code. Please check the code below and study OO concepts. I created a private class to represent the accounts. That way you can have an arraylist of account objects.
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication5 {
private static final class Account {
int accountno;
String name;
double balance;
#Override
public String toString() {
return "Account{" + "accountno=" + accountno + ", name=" + name + ", balance=" + balance + '}';
}
public void deposit(double amount){
balance = balance + amount;
}
void withdraw(double amount){
balance = balance-amount;
}
}
public static void AccountMenu() {
ArrayList<Account> a = new ArrayList();
Scanner in = new Scanner(System.in);
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
int number = in.nextInt();
while (!(number == 4)) {
switch (number) {
case 1: {
Account c = new Account();
System.out.println("Enter the Account no.");
c.accountno = in.nextInt();
System.out.println("Enter the name");
c.name = in.next();
System.out.println("Enter the Balance");
c.balance = in.nextDouble();
a.add(c);
break;
}
case 2: {
System.out.println("Account details are :");
for (Account b : a) {
System.out.println(b);
}
break;
}
case 3: {
System.out.println("Enter the account number");
int accountno = in.nextInt();
for (Account account : a) {
if (account.accountno == accountno) {
System.out.println(account);
}
}
break;
}
case 4:
System.out.println("Exit");
}
System.out.println("Enter the number for the following menu :1. Open Account 2. Show Account details "
+ "3.Retrieve details by Searching Account Number 4. Exit");
number = in.nextInt();
}
}
public static void main(String[] args) {
AccountMenu();
}
}

Is it possible to use a scanner this way?

Ok so, this is whats going on. I'm making a simple simple bank program.
This is what I want to do, notice the variables for my Account class (a1, a2, a3)
This works perfectly fine, but not for what I want to do.
In the switch cases, I want to be able to let the user input the name under the account and be able to edit it.
Now, I know if I were to basically do this:
Account AccountObject = new Account ();
balance.put (sc.nextLine(), AO.addFunds)
Then I would have separate users, but the funds would essentially all be the same. How would I make them separate*
I know once I figure out how to do this, I'll be set to move on to more complicated projects.
import java.util.Hashtable;
import java.util.Scanner;
class Data {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Scanner sc = new Scanner(System.in);
Scanner sa = new Scanner(System.in);
boolean quit = false;
boolean quit2 = false;
// Create account variables
Account a1 = new Account();
Account a2 = new Account();
Account a3 = new Account();
Account a4 = new Account();
Account a5 = new Account();
// Add funds to variables in Hashtable
balance.put(sc.nextLine(), a1.addFunds());
balance.put(sc.nextLine(), a2.addFunds());
balance.put(sc.nextLine(), a3.addFunds());
balance.put(sc.nextLine(), a4.addFunds());
balance.put(sc.nextLine(), a5.addFunds());
do {
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int input = sa.nextInt();
switch (input) {
case 1:
System.out.println(balance.get(sc.nextLine()));
break;
case 2:
System.out.println(balance.put(sc.nextLine(), a1.addFunds()));
break;
case 3:
System.out.println(balance.put(sc.nextLine(), a1.withdrawFunds(sa.nextDouble())));
break;
case 4:
quit = true;
break;
}
} while(!quit);
System.out.println("Exiting menu");
}
}
Account class
import java.util.Scanner;
public class Account {
int balance;
String name;
public double addFunds() {
Scanner sa = new Scanner(System.in);
double amount = sa.nextDouble();
balance += amount;
return balance;
}
public String Acct(String names) {
Scanner sc = new Scanner(System.in);
name = names;
return name;
}
public double withdrawFunds(double amount) {
balance -= amount;
return balance;
}
public String toString() {
return String.format("Balance: %n", balance);
}
}
You should create an Account class, which is model for an account. I suggest you do not handle the user input inside the Account class.
Account class
public class Account {
private String name;
private int balance;
public Account(String name, int startBalance) {
this.name = name;
this.balance = startBalance;
}
public void addFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
this.balance += amount;
}
public void withdrawFunds(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount must be absolute");
}
else if (amount > this.balance) {
throw new IllegalArgumentException("You don't have that, so you cannot grab that.");
}
this.balance -= amount;
}
public String getName() {
this.name;
}
public int getBalance() {
return this.balance;
}
}
Now, if you want, you can create some accounts and add them to an ArrayList<Account>. I do not know why you would use a HashMap: if you have just a list with all Account objects, you have all information you need.
ArrayList<Account> accounts = new ArrayList<Account>();
Scanner sc = new Scanner(System.in);
You can implement your user input like something like:
private static ArrayList<Account> accounts = new ArrayList<Account>();
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
initializeSomeBankAccounts();
displayUI();
}
private static void initializeSomeBankAccounts() {
for (int i = 0; i < 2; i++) {
System.out.print("Insert " + (i > 0 ? "another " : "") + "account name: ");
String name = sc.nextLine();
System.out.print("Insert start balance: ");
int startBalance = sc.nextInt();
sc.nextLine();
// Create a new account using the user input
Account account = new Account(name, startBalance);
// Add the account to our list with accounts.
accounts.add(account);
}
}
public static void displayUI() {
boolean quit = false;
while (!quit) {
// Show a menu with the available actions
System.out.println("Menu: \n 1: Check balance\n 2: Add funds\n 3: Withdraw funds\n 4: Quit");
int action = sc.nextInt();
sc.nextLine();
Account account;
// Since we ask the user to insert a right account name, we can
// guarantee that the variable 'account' contains an Account
// object.
switch (action) {
case 1:
account = askAccount();
System.out.println(account.getBalance());
break;
case 2:
account = askAccount();
System.out.print("Amount: ");
int amount = sc.nextInt();
account.addFunds(amount);
break;
case 3:
account = askAccount();
System.out.print("Amount: ");
amount = sc.nextInt();
account.withdrawFunds(amount);
break;
case 4:
quit = true;
break;
}
}
}
private static Account askAccount() {
System.out.println("Which account? ");
Account account = null;
boolean accountFound = false;
// Now the user has to input a valid account name, we're going to
// search for that account name in the list. If it is found, we
// have the whole Account object stored into the variable 'account'.
// Otherwise, if it is not found, then we repeat to ask to insert
// an account name, until a account name is given which is present
// in our list.
while (!accountFound) {
String accountName = sc.nextLine();
account = searchAccount(accountName);
if (account == null) {
System.out.println("Account not found. Insert another account:");
}
else {
accountFound = true;
}
}
return account;
}
/**
* Searches an account from our list of all accounts.
*
* #param name The name to search for.
* #return The account if found, or null otherwise.
*/
private static Account searchAccount(String name) {
for (Account account : accounts) {
if (account.getName().equals(name)) {
return account;
}
}
return null;
}
I also got a few suggestions:
You have some variables which are not used, i.e. quit2. You might want to remove them.
As far as I know, you do not need to have two Scanners; one is sufficient, since you can call both nextLine() and nextInt() on the same Scanner.
You have variables starting with an uppercase character, i.e. AccountObject. In Java, it is allowed, but the Java Naming Conventions prescribe that one should start variables with a lowercase letter.
You are using the class Hashtable, but it is recommended to use HashMap<Key, Value>.

bank account client in java with multiple classes

I am trying to make a bank account program, but I cannot figure out how to get all my variables visible to every class that I have, or how to make the withdrawal and deposit methods of my code visible. Can anyone look at my code and tell me what is wrong? I only want input and output in the client class.
Thanks
Client Class
public class Client {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your Name: ");
String cusName = input.nextLine();
System.out.println("Enter Account Type: ");
String type = input.next();
System.out.println("Enter Initial Balance: ");
int bal = input.nextInt();
BankAccount b1 = new BankAccount(cusName, num, type, bal);
int menu;
System.out.println("Menu");
System.out.println("1. Deposit Amount");
System.out.println("2. Withdraw Amount");
System.out.println("3. Display Information");
System.out.println("4. Exit");
boolean quit = false;
do {
System.out.print("Please enter your choice: ");
menu = input.nextInt();
switch (menu) {
case 1:
b1.deposit();
break;
case 2:
b1.withdraw();
System.out.println("Current Account Balance=" + Balance);
System.out.print("Enter withdrawal amount:");
amount = input.nextInt();
break;
case 3:
b1.display();
break;
case 4:
quit = true;
break;
}
} while (!quit);
}
}
Money Class
public class Money
{
static int accountNumber, Balance, amount;
Scanner input = new Scanner(System.in);
static String name, actype;
public int deposit() {
System.out.print("Enter depost amount:");
amount = input.nextInt();
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance + amount;
return 0;
}
int withdraw() {
if (Balance < amount) {
System.out.println("Not enough funds.");
return 1;
}
if (amount < 0) {
System.out.println("Invalid");
return 1;
}
Balance = Balance - amount;
return 0;
}
}
BankAccount Class
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
}
void display() {
System.out.println("Name:" + name);
System.out.println("Account No:" + accNo);
System.out.println("Balance:" + bal);
}
void dbal() {
System.out.println("Balance:" + bal);
}
}
Add Money to your BankAccount and create a getter method as:
class BankAccount {
Scanner input = new Scanner(System.in);
static String name, actype;
static int bal, amt;
Random randomGenerator = new Random();
int accNo = randomGenerator.nextInt(100);
Money money;
BankAccount(String name, int accNo, String actype, int bal) {
this.name = name;
this.accNo = accNo;
this.actype = actype;
this.bal = bal;
this.money = new Money();
}
public Money getMoney(){
return this.money;
}
.....
}
Use bankaccount.getMoney() to invoke deposit and withdraw as :
b1.getMoney().deposit();
b1.getMoney().withdraw();
In addition, I would advice to make the Money class attributes e.g. amount, accntType... non-static and set through through a constructor. Static variables are associated with class definition and hence you won't be abl to maintain them per Bank Account.
I'm not going to answer this question for you. Instead, I'm going to recommend that you read a bit more about Java programming concepts that will explain it to you, by default.
Here is one on encapsulation, which is the main concept that you're asking about
This is a great book on how to write code well, including things like keeping methods short
In particular, your main method should be broken into smaller pieces
Here's a stack overflow question that talks about it if you don't want to buy the book.
If you don't want to read any of these links, #YogendraSingh answered this question really well, use that answer.
Attributes to an object shouldn't be static, for example your "name, actype, bal and amt". Also I think your money class should exist and those methods could be in a bank account (you deposit/withdraw from a bank account).

Categories

Resources