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).
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 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();
}
}
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>.
For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.
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;