I'm trying to create an account class in java. My main issue is not with the class itself but with the output. In short I'm using an array to store bank account information and then checking for an id after to deposit/withdraw a certain amount. My issue is that when I try typing in an invalid value for the id (this is for the checking/searching portion) I should get an output of "account not found" however, for some reason I end up getting five outputs of the same line "account not found" (probably has to do something with the array size but I can't quite figure it out). Is there a way to get it to only print out the line once?
tl;dr: When typing an invalid Id I should only get one line of "account not found", getting multiple instead
import java.util.Scanner;
public class AccountDriver
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int id =0;
double balance = 0;
double interest = 0;
Account[] accounts = new Account[5];
//this part fills in the array by asking the user information about each account
System.out.println("Enter the annual interest rate ");
interest = kb.nextDouble();
for (int i = 0; i < 5; i++)
{
System.out.println("Enter the account number: ");
id = kb.nextInt();
System.out.println("Enter the initial amount to deposit: ");
balance = kb.nextDouble();
Account a = new Account(id,balance,interest);
accounts[i] = a;
}
boolean repeat = true;
boolean found = false;
while(repeat)
{
System.out.println("\n\n*******************************");
System.out.println("Welcome to the BANK OF AMERICA");
System.out.println("\n\n*******************************");
System.out.println("Enter the account number to deposit, withdraw money :");
id = kb.nextInt();
int i = 0;
while (!found && i < 5)
{
if(id == accounts[i].getId())
{
System.out.println("Here is the account information currently:");
System.out.println(accounts[i]);
System.out.println("*******************");
System.out.println("Enter the amount of deposit: ");
double depositAmount = kb.nextDouble();
accounts[i].deposit(depositAmount);
System.out.println("Enter the amount to withdraw: ");
double withdrawAmount = kb.nextDouble();
if(!accounts[i].withdraw(withdrawAmount))
{
System.out.println("*******Not enough money in your account*********");
}
else
{
System.out.println("Here is the account information after your transaction:");
System.out.println(accounts[i]);
}
}
**//confused about this part**
else
{
System.out.println("Account not found");
}
i++;
}
//this asks the user if they have any other accounts to continue running the program
System.out.println("\nDo you have any other account?");
String answer = kb.next();
if(answer.equalsIgnoreCase("no"))
{
repeat = false;
}
}
}
}
Here's the class if anyone needs it
public class Account{
//These are instance variables
private static double annualInterestRate;
private int id;
private double balance;
//This creates an object from the date class in java
private java.util.Date dateCreated;
//This no argument constructor creates a default account
public Account()
{
dateCreated = new java.util.Date();
id = 0;
balance = 0;
annualInterestRate = 0;
}
//This constructor creates an account with
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
//initialize the instance variables to the given values
dateCreated = new java.util.Date();
id = newId;
balance = newBalance;
annualInterestRate = newAnnualInterestRate;
}
//accessors (get)fill in the following methods
public int getId()
{
return id;
}
public double getBalance()
{
return balance;
}
public static double getAnnualInterestRate()
{
return annualInterestRate;
}
//mutators (get)
public void setId(int newId)
{
if (newId > 0)
{
id = newId;
}
}
public void setBalance(double newBalance)
{
if(newBalance >0)
{
newBalance = balance;
}
}
public static void setAnnualInterestRate(double newAnnualInterestRate)
{
if(newAnnualInterestRate > 0)
{
newAnnualInterestRate = annualInterestRate;
}
}
public double getMonthlyInterest()
{
double monthlyInterest = (balance * annualInterestRate/100 / 12);
return monthlyInterest;
}
public java.util.Date getDateCreated()
{
return dateCreated;
}
//this boolean method checks to see if the user has enough money to withdraw
public boolean withdraw(double amount)
{
if(amount > balance)
{
return false;
}
else
{
balance = balance - amount;
return true;
}
}
//this method returns the balance after the user enters an amount to deposit
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//this method compares two accounts
public boolean equals(Account a)
{
return this.id == a.id;
}
//this method outputs the account information for each account
public String toString()
{
String s = "";
s = s + "ID: " + id;
s = s + String.format("\nBalance: %.2f", balance);
s = s + "\nAnnual interest rate: " + annualInterestRate;
double value = getMonthlyInterest();
s = s + String.format( "\nmonthly interest: %.2f", value);
s = s + "\nDate account created: " + dateCreated;
return s;
}
}
Put a Break after your System.out.println();
else{
System.out.println("Account not found");
//this will break your loop;
break;
}
or set your found to true
else{
System.out.println("Account not found");
//this will stop your inner while loop;
found = true;
}
Updated
i found out a lot of lapses on your code.
fix #1 : put your boolean found = false; inside you outer loop while(repeat) because you are going to change the value of that boolean variable later on inside your inner while loop. move your boolean found = false; after this declaration int i = 0;
fix #2 : after your transaction ends put a found = true; after your System.out.println(accounts[i]);
reason : this is to stop your inner while loop.
fix #3 : on your else condition put a if condition that will verify if there are no more next account. before terminating your inner loop.
else{
// i == 4 will return true after the loop reached the last account.
if(i == 4){
System.out.println("Account not found");
// this is to stop the inner loop if no account found .
found = true;
}
}
Related
I am working on a java program that basically simulates a bank account to make deposits, withdraws, display balance, etc. I have done almost everything. I am just stuck in one part to be finished. The program asks the user what is the starting balance and interest rate. The only thing I am missing is that I need to display a message that the account is inactive when the balance goes under $25, that is done. Now I need a message saying that the account is ACTIVE but only once the balance went down under 25 and then came back over 25. Every way that I have tried it shows the active every time the balance is more than 25, I just need it to display once after coming back from being inactive but can't manage a way how to do it. Any ideas would be appreciated, here is my code:
///BankDemo class
import java.util.Scanner;
public class BankDemo {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float startingBalance;
float interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextFloat();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextFloat();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
while(startingBalance > -1) {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else {
System.out.print("Error, option not valid\n");
}
}
}
}
///BankAccount class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
float charge = 1;
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance += valueD;
numDeposits++;
}
public void withdraw() {
float valueW;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextFloat();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 25) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
float monRate = annualRate / 12;
float monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
///SavingsAccount class
public class SavingsAccount extends BankAccount {
private boolean active;
public SavingsAccount(float bal, float rate) {
super(bal, rate);
if(bal < 25)
active = false;
else
active = true;
}
public void withdraw() {
if(active)
super.withdraw();
}
public void deposit(float amount) {
if(!active) {
if(amount + balance < 25)
return;
}
super.deposit();
}
public void withdrawals() {
if(numWithdrawals > 4) {
monthlyServCharg += numWithdrawals - 4;
}
if(balance < 25)
active = false;
}
}
You show the messages only if the active status changes, i.e. when you deactivate the account:
if(balance < 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
And when you activate it again:
if( balance >= 25 && !active) {
//print message here
active = true;
}
To achieve that in BankAccount it already needs the active flag that SavingsAccount has (the subclass wouldn't need it then). You probably also want to disallow withdrawals if the account isn't active.
ATM Exercise
It asks the user to enter an id then checks the id if it's correct and displays the main menu which has four options.
The problem
The problem is that when the user chooses an option the program is over .. but what I need is that once the system starts it never stop until the user chooses 4 (which is the exit option ) and then starts all over again.
the question in the book
(Game: ATM machine) Use the Account class created in Programming Exercise 9.7 to simulate an ATM machine. Create ten accounts in an array with id 0, 1, . . . , 9, and initial balance $100. The system prompts the user to enter an id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is accepted, the main menu is displayed as shown in the sample run. You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu. Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not stop.
import java.util.Scanner;
public class Account {
private int id;
private double balance;
private static double annualIntrestRate;
private java.util.Date dateCreated;
public Account() {
}
public Account(int id) {
this.id = id;
balance = 100;
dateCreated = new java.util.Date();
}
public void setAnnualIntrest(double intrest) {
annualIntrestRate = intrest;
}
public void setBalance(double newBalance) {
balance = newBalance;
}
public void setID(int newID) {
id = newID;
}
public double getBalance() {
return balance;
}
public int getID() {
return id;
}
public java.util.Date getDate() {
return dateCreated;
}
public static double getMonthlyIntrestRate() {
return ((annualIntrestRate / 12) / 100);
}
public double getMonthlyIntrest() {
return (balance * getMonthlyIntrestRate());
}
public double withDraw(double withDrawAmount) {
return balance = balance - withDrawAmount;
}
public double deposit(double depositeAmount) {
return balance = balance + depositeAmount;
}
public static void main(String[] args) {
Account[] accounts = new Account[10];
for (int i = 0; i < accounts.length; i++) {
accounts[i] = new Account(i);
}
Scanner input = new Scanner(System.in);
System.out.print("Enter an ID: ");
int enteredID = input.nextInt();
while (enteredID != accounts[enteredID].getID()) {
System.out.print("enter correct id!");
enteredID = input.nextInt();
}
if (enteredID == accounts[enteredID].getID()) {
System.out.println("Main Menu: ");
System.out.println("1: check balance");
System.out.println("2: withdraw");
System.out.println("3: deposit");
System.out.println("4: exit");
System.out.print("Enter a choice: ");
int choice = input.nextInt();
if (choice == 1) {
System.out.println("The balance is: " + accounts[enteredID].getBalance());
} else if (choice == 2) {
System.out.print("Enter withdraw amount: ");
int withdrawAmount = input.nextInt();
accounts[enteredID].withDraw(withdrawAmount);
} else if (choice == 3) {
System.out.print("Enter deposit amount: ");
int depositAmount = input.nextInt();
accounts[enteredID].deposit(depositAmount);
} else if (choice == 4) {
System.out.print("Enter an ID: ");
enteredID = input.nextInt();
}
}
}
There are 2 fundamental parts of the question that you are missing in your program:
1) Once you exit, the system will prompt for an id again. Thus, once the system starts, it will not stop.
This means that once the real work in your main method starts (the first "enter an id"), there should be no way the program gets stopped internally; only through Ctrl-C if it is running in a terminal, or a "Stop" button if it is running in an IDE.
To implement this, you need an outer while loop:
while(true) {
// the rest of the code goes in here
}
around the whole body of "work" in your main method.
2) Once an id is accepted, the main menu is displayed as shown in the sample run. You can enter a choice 1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and 4 for exiting the main menu.
I am assuming this means that until option 4 is entered, the menu should keep reappearing after the user completes task 1, 2, or 3, meaning ANOTHER loop needs to be used for that part of the code, i.e.:
boolean shouldExit = false;
while (!shouldExit) {
// print menu and do your logic checking when a value is entered.
if (choice == 4) {
shouldExit = true; // This will break out of this loop, and go back to the first "enter an id".
}
}
Hopefully this helps guide you in the right direction.
import java.util.Scanner;
public class Account {
private int id;
private double balance;
private static double annualIntrestRate;
private java.util.Date dateCreated;
public Account() {
}
public Account(int id) {
this.id = id;
balance = 100;
dateCreated = new java.util.Date();
}
public void setAnnualIntrest(double intrest) {
annualIntrestRate = intrest;
}
public void setBalance(double newBalance) {
balance = newBalance;
}
public void setID(int newID) {
id = newID;
}
public double getBalance() {
return balance;
}
public int getID() {
return id;
}
public java.util.Date getDate() {
return dateCreated;
}
public static double getMonthlyIntrestRate() {
return ((annualIntrestRate / 12) / 100);
}
public double getMonthlyIntrest() {
return (balance * getMonthlyIntrestRate());
}
public double withDraw(double withDrawAmount) {
return balance = balance - withDrawAmount;
}
public double deposit(double depositeAmount) {
return balance = balance + depositeAmount;
}
public static void main(String[] args) {
Account[] accounts = new Account[10];
for (int i = 0; i < accounts.length; i++) {
accounts[i] = new Account(i);
}
Scanner input = new Scanner(System.in);
System.out.print("Enter an ID: ");
int enteredID = input.nextInt();
boolean shouldExit = false;
while (true) {
if (enteredID >9) {
System.out.print("enter correct id: ");
enteredID = input.nextInt();
}
if (enteredID == accounts[enteredID].getID()) {
System.out.println("Main Menu: ");
System.out.println("1: check balance");
System.out.println("2: withdraw");
System.out.println("3: deposit");
System.out.println("4: exit");
System.out.print("Enter a choice: ");
int choice = input.nextInt();
if (choice == 1) {
System.out.println("The balance is: " + accounts[enteredID].getBalance());
continue;
} else if (choice == 2) {
System.out.print("Enter withdraw amount: ");
int withdrawAmount = input.nextInt();
accounts[enteredID].withDraw(withdrawAmount);
continue;
} else if (choice == 3) {
System.out.print("Enter deposit amount: ");
int depositAmount = input.nextInt();
accounts[enteredID].deposit(depositAmount);
continue;
}
shouldExit = false;
while (!shouldExit) {
if (choice == 4) {
System.out.print("Enter an ID: ");
enteredID = input.nextInt();
shouldExit = true;
}
}
}
}
}
}
Try below code:
import java.util.Scanner;
public class Account {
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
public Account() { }
public Account(int id) {
this.id = id;
this.balance = 100;
this.dateCreated = new java.util.Date();
}
public void setAnnualInterest(double interest) {
annualInterestRate = interest;
}
public void setBalance(double newBalance) {
balance = newBalance;
}
public void setID(int newID) {
id = newID;
}
public double getBalance() {
return balance;
}
public int getID() {
return id;
}
public java.util.Date getDate() {
return dateCreated;
}
public static double getMonthlyInterestRate() {
return ((annualInterestRate / 12) / 100);
}
public double withDraw(double withDrawAmount) {
return balance = balance - withDrawAmount;
}
public double deposit(double depositAmount) {
return balance = balance + depositAmount;
}
public static void main(String[] args) {
Account[] accounts = new Account[10];
for (int i = 0; i < accounts.length; i++) {
accounts[i] = new Account(i);
}
Scanner input = new Scanner(System.in);
System.out.print("Enter an ID: ");
int enteredID;
do {
enteredID = input.nextInt();
if (enteredID <= 9 && enteredID >=0 && enteredID == accounts[enteredID].getID()) {
System.out.println("Main Menu: ");
System.out.println("1: check balance");
System.out.println("2: withdraw");
System.out.println("3: deposit");
System.out.println("4: exit");
do {
System.out.print("Enter a choice: ");
int choice = input.nextInt();
input.nextLine();
if (choice == 1) {
System.out.println("The balance is: " + accounts[enteredID].getBalance());
} else if (choice == 2) {
System.out.print("Enter withdraw amount: ");
int withdrawAmount = input.nextInt();
accounts[enteredID].withDraw(withdrawAmount);
} else if (choice == 3) {
System.out.print("Enter deposit amount: ");
int depositAmount = input.nextInt();
accounts[enteredID].deposit(depositAmount);
} else if (choice == 4) {
System.out.println("Exit");
System.out.println("Enter an ID");
break;
}
} while (true);
}
else{
System.out.print("enter correct id!");
}
}while(true);
}
}
I recommend to use switch statement instead of if-else ladder
// same as above code
System.out.print("Enter a choice: ");
int choice = input.nextInt();
input.nextLine();
switch(choice) {
case 1:
System.out.println("The balance is: " + accounts[enteredID].getBalance());
break;
case 2:
System.out.print("Enter withdraw amount: ");
int withdrawAmount = input.nextInt();
accounts[enteredID].withDraw(withdrawAmount);
break;
case 3:
System.out.print("Enter deposit amount: ");
int depositAmount = input.nextInt();
accounts[enteredID].deposit(depositAmount);
break;
case 4:
System.out.println("Exit");
System.out.println("Enter an ID");
break;
}
} while (true);
}
I am creating a program that has a ATM class in which there is a cheqings and savings account that can be changed based on what the user inputs in the main method in the starting class. For some reason when the user enters in the amount to deposit/withdraw from their account the math is done but the value is not stored. therefor when I go to display the account balance both accounts are at their starting values.
public class ATM {
private double cheqBal;
private double savingsBal;
private String bankName;
public ATM(double cheq, double savings, String name) {
cheqBal = cheq;
savingsBal = savings;
bankName = name;
}
public double getCheq() {
return cheqBal;
}
public double getSavings() {
return savingsBal;
}
public String getName() {
return bankName;
}
public void setCheq(double cheq) {
cheqBal = cheq;
}
public void setSavings(double savings) {
savingsBal = savings;
}
public void setName(String name) {
bankName = name;
}
public double depositCheq(double cheq) {
if (cheq < 0) {
System.out.println("Sorry you cannot do that!");
} else {
cheqBal += cheq;
}
System.out.println(getCheq());
return cheqBal;
}
There is the ATM class where the methods for depositing/withdrawing money are. I only showed the deposit chequing method.
double savBal = 500;
double cheqBal = 1000;
ATM bank1 = new ATM(cheqBal, savBal, "BMO");
String userChoice = JOptionPane.showInputDialog("1: Deposit Cheqings \n2: Deposit Savings \n"
+ "3: Withdraw Cheqings \n4: Withdraw Savings \n5: Show Balance\n6: Exit");
int choice = Integer.parseInt(userChoice);
if (choice == 1) {
String cheqIn = JOptionPane.showInputDialog("How much would you like to deposit?: ");
bank1.depositCheq(Double.parseDouble(cheqIn));
cheqBal = bank1.getCheq();
} else if (choice == 2) {
String savIn = JOptionPane.showInputDialog("How much would you like to deposit?: ");
bank1.depositSavings(Double.parseDouble(savIn));
savBal = bank1.getSavings();
} else if (choice == 3) {
String cheqOut = JOptionPane.showInputDialog("How much would you like to withdraw?: ");
bank1.withdrawCheq(Double.parseDouble(cheqOut));
cheqBal = bank1.getCheq();
} else if(choice == 4){
String savOut = JOptionPane.showInputDialog("How much would you like to withdraw?: ");
bank1.withdrawSavings(Double.parseDouble(savOut));
savBal = bank1.getSavings();
}else if(choice == 5){
bank1.toString();
}else if(choice == 6){
break;
There is the main method. When i hit 1 to deposit money it does not reiterate the amount I deposited when i hit 5 to show balance. (all of the main method is in a loop so it continues until exit).
Sorry for the large amount of code, hope you guys understand my problem and can help!
You are constructing a new ATM object every time you run the loop, with the starting values passed to the constructor, so you display the values of this new object and the old one gets destroyed.
Im writing a simple program to illustrate classes and inheritance in java. The program is Bank that has 2 classes Account and Operation where Operation extends Account. Now in main I declared the values in Account and then I started calling the operations from Operation class. now whenever Operation calls the values in Account it return 0 for int and null for string though I added value to it.
Here is the Account:
public class Account {
private String Name;
private int ID;
private double Money;
Account()
{
}
Account (String n, int i, double m)
{
Name = n;
ID = i;
Money = m;
}
public void setMoney(double m)
{
Money = m;
}
public double getMoney()
{
return Money;
}
public int getID()
{
return ID;
}
public String getName()
{
return Name;
}
public void Check()
{
System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}
}
Here is the Operation class:
import java.util.Date;
public class Operation extends Account{
private Date TransactionDate;
public void Withdraw(double amount)
{
double Money = getMoney();
if (amount > Money)
System.out.println("The amount is insufficient");
else
{
Money = Money - amount;
TransactionDate = new Date();
setMoney(Money);
System.out.println("The available money is " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));
}
}
public void Deposit(double amount)
{
double Money = getMoney();
if (amount < 0)
System.out.println("You cant add minus");
else
{
Money = Money + amount;
TransactionDate = new Date();
setMoney(Money);
System.out.println("Your credits are: " + String.valueOf(Money) + " at " + String.valueOf(TransactionDate));
}
}
public void Check()
{
String Name = getName();
int ID = getID();
double Money = getMoney();
System.out.println("Your Name is: " + Name + " Your ID is: " + String.valueOf(ID) + " Your Balance is: " + String.valueOf(Money));
}
}
Here is the main:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
/**
* #param args
* #throws IOException
* #throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your ID");
int ID = Integer.parseInt(br.readLine());
System.out.println("Enter your Name");
String Name = br.readLine();
System.out.println("Enter your Money");
double Money = Double.parseDouble(br.readLine());
Account a = new Account(Name, ID, Money);
a.Check();
Operation o = new Operation();
while (true) {
System.out.println("\n-----------------------------------");
System.out
.println("Enter 1 to withdraw, 2 to Deposit, 3 to Check, 4 to exit ");
int operation = Integer.parseInt(br.readLine());
switch (operation) {
case 1:
System.out.println("enter the amount");
double withdrawMoney = Double.parseDouble(br.readLine());
o.Withdraw(withdrawMoney);
break;
case 2:
System.out.println("enter the amount");
double Depositmoney = Double.parseDouble(br.readLine());
o.Deposit(Depositmoney);
break;
case 3:
o.Check();
break;
case 4:
break;
default:
System.out.println("enter between 1 and 4 only");
}
if (operation == 4)
break;
}
}
}
I really don't know why Operation cant read the values I added to Account since Operation extends Account can you please explain it to me the reason and how to fix it.
Thanks in advance.
You have two separate objects -- one an Account, and one an Operation.
An instance of your Operation class has a name, ID and money - but they're not the same name, ID and money as other instances of Account or Operation.
One way to fix it would be to add a constructor to Operation:
class Operation {
Operation(String n, int i, double m) {
super( n, i, m );
}
...
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am almost done with an assignment. I am creating a Bank program, and I have almost everything done. The part that I am stuck on is the transactions part. I have to create a function public String getTransactionInfo(int n) which returns the last n transactions of a bank account. I cannot seem to figure this part out. i have a variable private int numOfTransactions and I tried incorporating that into the function, but it didn't work. this is what I tried.
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
that did not work. cannot figure out how to return this is a string. any ideas?
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
//case 5: ... break;
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactions[0] = balance;
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
numOfTransactions++;
}
}
}
}//end of class
}
I think the correct solution to your problem will be something like this:
public String gettransactionInfo(int n)
{
//Traverse the "transactions" array in *reverse* order
//In For loop start with transactions.length, and decrement by 1 "n" times
// Append the transaction amount to a String
// Return the string.
}
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
Hehe! What are you exactly trying to do here? :) ... You messed up the rvalue and lvalue, but that's not related to the answer.
The key is to have a String Array in the class. Every time a transaction happens append the transaction details to the array..... Then gettransactionInfo should print the last n details in the string...
e.g.
transInfo[0] = "A deposited 30K"
transInfo[1] = "B withdrew 20K"
transInfo[2] = "C deposited 5k"
Last 1 transaction displays the last entry in the string "C deposited 5k"
If you want to return the number of transactions as a String, as opposed to the integer (which you have it stored as), then you want to convert the integer to a String.
In Java, you would do so via:
Integer.toString(numOfTransactions)
Side note: Out of curiosity, in your program, why are you doing this?
public String gettransactionInfo(int n)
{
numOfTransactions = n;
return n;
}
That is inefficient and wrong since you are setting the numberOfTransactions to the n value. That functionality, by convention is put in a setter method, as opposed to a getter method - which is what your implementation is supposed to do.
Ideally, it should be:
public String gettransactionInfo()
{
return Integer.toString(numOfTransactions);
}
EDIT:
As per the comments, the correct thing to do would be to return an index from the transactions array, corresponding to index n.
Where, in this case the transactions array should be a String array.
EDIT 2:
In the case where you use a separate string array, you would update it (depending on the transaction) as follows:
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Bank myBank = new Bank();
int user_choice = 2;
do {
//display menu to user
//ask user for his choice and validate it (make sure it is between 1 and 6)
System.out.println();
System.out.println("1) Open a new bank account");
System.out.println("2) Deposit to a bank account");
System.out.println("3) Withdraw to bank account");
System.out.println("4) Print short account information");
System.out.println("5) Print the detailed account information including last transactions");
System.out.println("6) Quit");
System.out.println();
System.out.print("Enter choice [1-6]: ");
user_choice = s.nextInt();
switch (user_choice) {
case 1: System.out.println("Enter a customer name");
String cn = s.next();
System.out.println("Enter a opening balance");
double d = s.nextDouble();
System.out.println("Account was created and it has the following number: " + myBank.openNewAccount(cn, d));
break;
case 2: System.out.println("Enter a account number");
int an = s.nextInt();
System.out.println("Enter a deposit amount");
double da = s.nextDouble();
myBank.depositTo(an, da);
break;
case 3: System.out.println("Enter a account number");
int acn = s.nextInt();
System.out.println("Enter a withdraw amount");
double wa = s.nextDouble();
myBank.withdrawFrom(acn, wa);
break;
case 4: System.out.println("Enter a account number");
int anum = s.nextInt();
myBank.printAccountInfo(anum);
break;
case 5: System.out.println("Enter a account number");
anum = s.nextInt();
myBank.printTransactionInfo(anum);
break;
default: System.out.println("Invalid option. Please try again.");
}
}
while (user_choice != '6');
}
static class Bank {
private BankAccount[] accounts; // all the bank accounts at this bank
private int numOfAccounts; // the number of bank accounts at this bank
//Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
accounts = new BankAccount[100];
numOfAccounts = 0;
}
// Creates a new bank account using the customer name and the opening balance given as parameters
// and returns the account number of this new account. It also adds this account into the account list
// of the Bank calling object.
public int openNewAccount(String customerName, double openingBalance) {
BankAccount b = new BankAccount(customerName, openingBalance);
accounts[numOfAccounts] = b;
numOfAccounts++;
return b.getAccountNum();
}
// Withdraws the given amount from the account whose account number is given. If the account is
// not available at the bank, it should print a message.
public void withdrawFrom(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].withdraw(amount);
System.out.println("Amount withdrawn successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Deposits the given amount to the account whose account number is given. If the account is not
// available at the bank, it should print a message.
public void depositTo(int accountNum, double amount) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
accounts[i].deposit(amount);
System.out.println("Amount deposited successfully");
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer name and the balance of the bank account whose
// account number is given. If the account is not available at the bank, it should print a message.
public void printAccountInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
return;
}
}
System.out.println("Account number not found.");
}
public void printTransactionInfo(int accountNum) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println("Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
}
}
System.out.println("Account number not found.");
}
// Prints the account number, the customer number and the balance of the bank account whose
// account number is given, together with last n transactions on that account. If the account is not
// available at the bank, it should print a message.
public void printAccountInfo(int accountNum, int n) {
for (int i =0; i<numOfAccounts; i++) {
if (accountNum == accounts[i].getAccountNum() ) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(accounts[i].getTransactionInfo(n));
return;
}
}
System.out.println("Account number not found.");
}
}
static class BankAccount{
private int accountNum;
private String customerName;
private double balance;
private double[] transactions;
private String[] transactionsSummary;
private int numOfTransactions;
private static int noOfAccounts=0;
public String getAccountInfo(){
return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
}
public String getTransactionInfo(int n)
{
String transaction = transactionsSummary[n];
if (transaction == null) {
return "No transaction exists with that number.";
}
else {
return transaction;
}
}
public BankAccount(String abc, double xyz){
customerName = abc;
balance = xyz;
noOfAccounts ++;
accountNum = noOfAccounts;
transactions = new double[100];
transactionsSummary = new String[100];
transactions[0] = balance;
transactionsSummary[0] = "A balance of : $" + Double.toString(balance) + " was deposited.";
numOfTransactions = 1;
}
public int getAccountNum(){
return accountNum;
}
public int getNumberOfTransactions() {
return numOfTransactions;
}
public void deposit(double amount){
if (amount<=0) {
System.out.println("Amount to be deposited should be positive");
} else {
balance = balance + amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was deposited.";
numOfTransactions++;
}
}
public void withdraw(double amount)
{
if (amount<=0){
System.out.println("Amount to be withdrawn should be positive");
}
else
{
if (balance < amount) {
System.out.println("Insufficient balance");
} else {
balance = balance - amount;
transactions[numOfTransactions] = amount;
transactionsSummary[numOfTransactions] = "$" + Double.toString(amount) + " was withdrawn.";
numOfTransactions++;
}
}
}
}//end of class
}
To convert an integer to a String:
String out = Integer.toString(n);
You description of case 5 is
Print the detailed account information including last transactions
Just returning the number of transactions as a string is not going to achieve that.
You need to store every transaction as it happens in the transactions array in your BankAccount class and then get the last n values in that array in the gettransactionInfo() function.
EDIT:
And btw, you have forgotten to call the openNewAccount() function
Convert primitive int to its wrapper class and call its toString() method
public String gettransactionInfo(int n) {
return new Integer(n).toString();
}