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");
}
Related
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());
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.
I am working a programming project from Java textbook that says:
The L&L bank can handle up to 30 customers who have savings accounts. Design and implement a program that manages the accounts. Keep track of key information and let each customer make deposits and withdrawals. Produce error messages for invalid transactions. Hint: You may want to base your accounts on the Account class from Chapter 4. Also provide a method to add 3 percent interest to all accounts whenever the method is invoked.
I am not certain on what the question is specifically asking but my guess is to allow and enable the user to add accounts, deposit, withdraw, add interest, get balance, and print the accounts being managed into an array. I am not entirely sure that I have to make an array but the whole chapter is on arrays.
My problem is that I am not sure how to enable the user to make an account
(EX: Account acct1 = new Account ("Ted Murphy", 72354, 102.56);),
to deposit money (EX: acct1.deposit (25.85);),
withdraw money (EX: acct3.withdraw (800.00, 0.0);),
add interest (EX: acct1.addInterest();),
or to print an array for all the accounts.
Here is the Account class found in the Java textbook with all the methods:
//********************************************************************
// Account.java Author: Lewis/Loftus/Cocking
//
// Represents a bank account with basic services such as deposit
// and withdraw.
//********************************************************************
import java.text.NumberFormat;
public class Accounts
{
private NumberFormat fmt = NumberFormat.getCurrencyInstance();
private final double RATE = 0.035; // interest rate of 3.5%
private int acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Accounts (String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Validates the transaction, then deposits the specified amount
// into the account. Returns the new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount is invalid.");
System.out.println (acctNumber + " " + fmt.format(amount));
}
else
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Validates the transaction, then withdraws the specified amount
// from the account. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
amount += fee;
if (amount < 0) // withdraw value is negative
{
System.out.println ();
System.out.println ("Error: Withdraw amount is invalid.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: " + acctNumber);
System.out.println ("Requested: " + fmt.format(amount));
System.out.println ("Available: " + fmt.format(balance));
}
else
balance = balance - amount;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
public double addInterestAll ()// I made this method myself but I am not sure if it is correct
{
balance += (balance * 0.03);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns the account number.
//-----------------------------------------------------------------
public int getAccountNumber ()
{
return acctNumber;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
}
}
Here is the main method that is under construction and I am not sure if I am on the right track:
import java.util.Scanner;
public class SixSix
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Input (0) to add account, (1) to deposit,");
System.out.println("(2) to withdraw, (3) to add interest, (4) to add interest to all");
System.out.println("(5) to get balance, (6) to get account number, (7) to print");
int input = scan.nextInt();
while (input == 0){
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
System.out.println("Please enter your account number");
int accNum = scan.nextInt();
System.out.println("Please Enter account balance");
double accBalance = scan.nextDouble();
//System.out.format
}
while (input == 1)
{
System.out.println("To deposit money to an account");
}
while (input == 2)
{
System.out.println("To withdraw money from an account");
}
while (input == 3)
{
System.out.println("To add Interest");
}
while (input == 4)
{
System.out.println("To add Interest to all");
}
while (input == 5)
{
System.out.println("To get balance");
}
while (input == 6)
{
System.out.println("To get account number");
}
while (input == 7)
{
System.out.println("Printing account");
}
}
}
It seems to me like you're on the right track. I'm inferring from the way the question (in the book) is phrased and the code that you've posted that the accounts don't already exist, in which case you need to allow the user of the system to create them. Then when altering an account, the user would first have to supply the account number so that you can identify the proper Accounts object.
I'm guessing that since the chapter was on arrays, it probably hasn't covered Maps yet (which would otherwise be a convenient way of associating account numbers to Accounts objects). If you use arrays, then having the account numbers range from 0 to 29 seems like a good idea.
Here's an example of how you could implement an AccountsManager class that helps you add and retrieve accounts from an array of accounts.
public class AccountsManager {
private Accounts[] accounts;
private final int capacity;
private int current;
public AccountsManager(int capacity) {
this.capacity = capacity;
accounts = new Accounts[capacity];
current = 0;
}
// returns the account number of the new account
// or -1 if no account could be made
public int addAccount(String name) {
if (current >= capacity) {
return -1;
}
accounts[current] = new Accounts(name, current, 0);
return current++;
}
public Accounts getAccount(int number) {
if (number >= current || number < 0) {
return null;
}
return accounts[number];
}
}
In the above, the capacity attribute is simply the size of the array, which is the maximum number of Accounts objects that can be created (this should be 30, according to the exercise). The current attribute (feel free to rename to something more informative!) keeps track of where in the array the next Accounts object should be created. This grows by one each time an account is added.
In your code, you could now do something like this:
AccountsManager manager = new AccountsManager(30);
// ...
if (input == 0) {
// Create new account
System.out.println("To create an account, please enter your name");
String name = scan.nextLine();
int accountNumber = manager.addAccount(name);
if (accountNumber == -1)
System.out.println("The bank can't handle any more accounts.");
else
System.out.println("Your account number is "+accountNumber);
} else if (input == 1) {
// Deposit money to account
System.out.println("What is your account number?");
int accountNumber = scan.nextInt();
// Check if account exists
if (manager.getAccount(accountNumber) == null) {
System.out.println("That account doesn't exist!");
} else {
System.out.println("How much do you want to deposit?");
double amount = scan.nextDouble();
manager.getAccount(accountNumber).deposit(amount);
}
}
Perhaps it might be preferable to create new methods in the AccountsManager class to make deposits etc, but this shows at least what the general structure could be like.
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).
I have a really long problem. I am creating a bank account and setting the balance to 0. If the user chooses to withdraw or deposit money to the account, the balance never changes. I choose to show the balance and it still says 0. This is probably a no brainer but I am spent right now. Here is my long code(The switch statement is in my main class and the methods are in an object class):
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
double balance = 0, amount = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
while (option != 0) {
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance(balance);
break;
case 3: //withdraw money
acc.withdraw(balance, amount);
break;
case 4: //deposit money
acc.deposit(balance, amount);
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
System.out.println(menu);
System.out.print("\tEnter your selection: ");
option = scan.nextInt();
}
And these are the methods I am calling:
public class Account{
Scanner input = new Scanner (System.in);
public Account(){
}
public void getID(int id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(double balance){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(double amount, double balance){
System.out.println("How much do you want to withdraw?:\t$");
amount = input.nextDouble();
balance -= amount;
return balance;
}
public double deposit(double amount, double balance){
System.out.println("How much do you want to deposit?:\t");
amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
The variable double balance cannot be passed as a reference. It does a copy so when you try to manipulate it, it won't affect the original that you pass as an argument. You need to update the value using the return value that you have in the function.
In order to make it work, you should do:
case 4: //deposit money
// note here that you need to update the balance variable using the return value that
// you put in the function
balance = acc.deposit(balance, amount);
break;
Note: Your design separating the balance from the Account class is not ideal per #Psyrus's answer. You should keep the balance as part of the Account class. The reason being that balance is part of the account and if your program grows to handle multiple accounts (just for the sake of examples), separating the variable balance from the account would create maintenance headache (imagine that with two instances of Account, you will have balance1 and balance2 variables (or whatever you will call it) in MyProgram2, the main application). While I gave the cause of your problem in regards of variable passing, you should refactor your code to follow #Psyrus suggestion.
You have your whole Account class set up but without the actual balance variable inside it. Move that variable from your program to your class and it should work. Upon looking further, you have kind of jumbled up bits between the two so do this:
public class MyProgram2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in);
String menu, outputString, poo;
int option = 1;
int id = 0;
Account acc = new Account();
menu ="\n\t1 Create Account and ID" +
"\n\t2 Check balance" +
"\n\t3 Withdraw" +
"\n\t4 Deposit" +
"\n\t5 Get account ID" +
"\n\t6 Display Account Info" +
"\n\t0 Quit\n\n\n";
do {
System.out.println(menu);
System.out.println("\tEnter your selection: ");
option = scan.nextInt();
switch (option) {
case 1: //Create an account and set ID
System.out.print("Enter Your Account ID to create account:\t");
id = input.nextInt();
System.out.println("Account created!");
break;
case 2: //check balance
acc.checkBalance();
break;
case 3: //withdraw money
acc.withdraw();
break;
case 4: //deposit money
acc.deposit();
break;
case 5: //get account id
acc.getID(id);
break;
case 7: //display account info
System.out.print("option 7");
break;
default: outputString = "\nInvalid Selection\n";
System.out.println(outputString);
break;
}
} while (option != 0);
}
}
public class Account{
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner (System.in); double balance = 0;
public Account(){
}
public void getID(id){
System.out.println("Your account ID is:\t" + id);
}
public void checkBalance(){
System.out.println("Your balance is:\t$" + balance);
}
public double withdraw(){
System.out.println("How much do you want to withdraw?:\t$");
double amount = input.nextDouble();
balance -= amount;
}
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
double amount = input.nextDouble();
balance += amount;
return balance;
}
public void getAccountInfo(int id, double balance){
}
}
That is one way of doing it, but like I say, your design is a bit of a cross between classes. You should try to keep all properties for an object within that class and create functions for that class to obtain / modify the properties. Printing to the user should be contained in the class responsible for giving the user the interface.
Edit: Oops forgot the while at the end of the do while loop...
You just need to modify the instance you created like this:
public double deposit(){
System.out.println("How much do you want to deposit?:\t");
this.amount = input.nextDouble();
this.balance += amount;
return balance;
}
The this keyword refers to the object that is calling this method in this case acc, so this.amount will modify the amount for that instance.
In your current code, you are just modifying the local variables.
You also need to update your Account class to have the amount and balance attributes:
public class Account{
Scanner input = new Scanner (System.in);
double balance = 0, amount = 0;