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.
Related
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 cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.
public class ATM {
public static Scanner kbd;
public static void main(String[] args) {
String acctNum, acctPword;
String balance;
int x = 1;
kbd = new Scanner(System.in);
System.out.print("Enter your account number: ");
acctNum = kbd.nextLine();
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
balance = checkID(acctNum, acctPword);
double balance1 = Double.parseDouble(balance);
System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************
while (balance.equals("error") && x <4){
System.out.println("Wrong password try again.");
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
x++;
}
if (x == 4)
System.out.println("Maximum number of attempts reached, Please try again later.");
if (x == 1){
menu();
}
kbd.close();
}
/**
* Determines if acctNum is a valid account number, and pwd is the correct
* password for the account.
* #param acctNum The account number to be checked
* #param pwd The password to be checked
* #return If the account information is valid, returns the current account
* balance, as a string. If the account information is invalid, returns
* the string "error".
*/
public static String checkID(String acctNum, String pwd)
{
String result = "error";
// Strings a, b, and c contain the valid account numbers and passwords.
// For each string, the account number is listed first, followed by
// a space, followed by the password for the account, followed by a space,
// followed by the current balance.
String a = "44567-5 mypassword 520.36";
String b = "1234567-6 anotherpassword 48.20";
String c = "4321-0 betterpassword 96.74";
if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
result = "520.36";
return result;
}
if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
result = "48.20";
return result;
}
if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
result = "96.74";
return result;
}
return result;
}
public static void menu(){
int x = 0;
double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.
System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
x = kbd.nextInt();
switch(x){
case 1:
displayBalance(acctBal);
break;
case 2:
deposit(acctBal, deposit);
break;
case 3:
withdraw(acctBal, withAmnt);
break;
case 4:
System.out.println("Have a nice day.");
break;
}
}
public static double deposit(double acctBal, double depAmnt){
System.out.print("How much money would you like to deposit? $");
depAmnt = kbd.nextDouble();
acctBal = acctBal + depAmnt;
System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
return acctBal;
}
public static double withdraw(double acctBal, double withAmnt){
System.out.print("How much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
if (acctBal <= 0){
System.out.println("You do not have any money.");
return acctBal;
}
if (acctBal < withAmnt){
System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
}
else{
acctBal = acctBal - withAmnt;
}
return acctBal;
}
public static double displayBalance(double balance){
System.out.println("Your balance is $" + String.format("%.2f", balance));
return balance;
}
You can change the menu() method to accept a parameter (called balance) and pass the value from main while calling menu() method, e.g.:
public static void menu(double acctBal){
double deposit = 0.0; //Other variables
}
And call it from main with balance, e.g.:
if (x == 1){
menu(balance);
}
Your code has a problem, you do not treat the situation where checkID returns "error". You cannot assign "error" to some String and then try to convert a double from that String.
Minor fix
balance = checkID(acctNum, acctPword);
double balance1 = 0.0;
if (balance.equals("error"))
{
// TODO: do something with invalid number.
}
else
{
balance1 = Double.parseDouble(balance);
}
System.out.println("You currently have $" + String.format("%.2f",balance1));
I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once
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;
}
}
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();
}