Creating a Bank program [closed] - java

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();
}

Related

Multiple User Defined Exceptions in java

So the scenario is to limit a user to perform three transactions a day, I wanted to finish the part where the exception is to be raised any help would be appreciated.
import java.util.Scanner;
class FundsNotAvailable extends Exception{
FundsNotAvailable(String s){
super(s);
}
}
class ExceededTransactionsLimit extends Exception{
ExceededTransactionsLimit(String s){
super(s);
}
}
class BankMethods {
String accName;
String accNumber;
Integer balance;
public Integer transactions = 0;
Scanner sc = new Scanner(System.in);
void AccOpen()
{
System.out.println("Enter Account Holder Name: ");
accName = sc.next();
System.out.println("Enter Account Number: ");
accNumber = sc.next();
System.out.println("Enter the Deposit amount: ");
balance = sc.nextInt();
}
void Deposit()
{
Integer amount;
System.out.println("Enter the Amount you wish to Deposit:");
amount = sc.nextInt();
balance = balance + amount;
}
void Withdrawal() throws FundsNotAvailable, ExceededTransactionsLimit
{
Integer amount;
System.out.println("Enter the Amount you wish to Withdraw:");
amount = sc.nextInt();
if (amount > balance)
{
throw new FundsNotAvailable("Insufficient Funds");
}
if(transactions > 3)
{
throw new ExceededTransactionsLimit("You have exceeded the daily transactions limit");
}
balance = balance - amount;
System.out.println(transactions);
}
void showBalance()
{
System.out.println("The Balance in your Account is:" + balance);
}
}
public class Bank
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BankMethods BM = new BankMethods();
BM.AccOpen();
Integer choice;
do {
System.out.println("Main Menu \n 1. Deposit \n 2. Withdraw \n 3. Show Balance \n 4. Exit");
System.out.println("Please Make A Choice:");
choice = sc.nextInt();
switch (choice) {
case 1:
BM.Deposit();
break;
case 2:
try {
BM.Withdrawal();
} catch (ExceededTransactionsLimit | FundsNotAvailable e) {
System.out.println(e.getMessage());
}
break;
case 3:
BM.showBalance();
break;
case 4:
System.out.println("Good Bye");
break;
}
}
while (choice != 4);
}
}
the condition transactions > 3 is working fine when i run it in the main class but isnt throwing an exception when i run it in the method i even tried to keep track of the transcations variable value and it kept increasing everytime i performed the withdraw operation.
Thank you (any help is appreciated)
no where in the code, value of transactions variable is getting updated.
Please add transactions++; in your Withdrawal() function and it will start working.

Java OOP exercise

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);
}

Using Linked List as the output?

I'm trying to write a bank account that asks the user if they want to see records, remove records, and other stuff. This is what I'm trying to produce
My program is nearly done the only problem I'm having is getting the output. I'm getting some weird error when i tried producing the output. When the output works. I'll put it inside a linked list.
public class Bank
{
public static void main(String args[]){
ArrayList<Customer> accounts = new ArrayList<Customer>();
Customer customer1 = new Customer(1, "Savings", "Dollars", 800);
Customer customer2 = new Customer(2, "Checking", "Euro", 1900);
Customer customer3 = new Customer(3, "Checking", "Pound", 8000);
accounts.add(customer1);
accounts.add(customer2);
accounts.add(customer3);
int customerID=4;
String choice;
int deposit;
int withdraw;
Scanner in = new Scanner(System.in);
Customer operation = new Customer();
boolean flag = true;
String accountType;
String currencyType;
int balance;
while(flag){
System.out.println("Select a choice:");
System.out.println("1. Existing customer");
System.out.println("2. New customer");
System.out.println("3. Quit");
String input = in.next();
//existing user
if(input.equals("1")){
System.out.println("Enter CustomerID: ");
customerID = in.nextInt();
System.out.println("Would you like to: ");
System.out.println("1. Deposit ");
System.out.println("2. Withdraw ");
System.out.println("3. Display account info ");
System.out.println("4. Check balance ");
choice = in.next();
if(choice.equals("1")){
System.out.println("How much would you like to deposit?");
deposit = in.nextInt();
operation.deposit(deposit);
}
else if (choice.equals("2")){
System.out.println("How much would you like to withdraw?");
withdraw = in.nextInt();
operation.withdraw(withdraw);
}
else if (choice.equals("3")){
operation.display(accounts.get(customerID));
}
else if (choice.equals("4"))
operation.balance(accounts.get(customerID));
else
System.out.println("Invalid");
}
//new user
else if(input.equals("2")){
//add new user to arraylist
int newID = customerID + 1;
System.out.println("Enter account type: ");
accountType = in.next();
System.out.println("Enter currency type: ");
currencyType = in.next();
System.out.println("Enter initial balance: ");
balance = in.nextInt();
System.out.println("Your customer ID will be: " + newID);
accounts.add(new Customer(newID, accountType, currencyType, balance));
}
else if(input.equals("3")){
System.out.println("Thanks for using this bank!");
flag = false;
}
else{
System.out.println("Invalid");
}
}
}
}
My second class:
public class Customer
{
String accountType, currencyType, info;
public int customerID, balance, amount;
Scanner input = new Scanner(System.in);
public Customer(int customerID, String accountType, String currencyType, int balance)
{
this.accountType = accountType;
this.currencyType = currencyType;
this.customerID = customerID;
this.balance = balance;
this.amount = amount;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public int deposit(int amount){
amount = input.nextInt();
if (amount >= 500) {
System.out.println("Invalid");
}
else{
balance = balance + amount;
}
return balance;
}
public int withdraw(int amount){
if (balance < amount) {
System.out.println("Invalid amount.");
}
else if (amount >= 500) {
System.out.println("Invalid");
}
else {
balance = balance - amount;
}
return balance;
}
public void display(ArrayList<Customer> accounts)
{
System.out.println("CustomerID:" + accounts.customerID);
System.out.println("Account Type:" + accounts.accountType);
System.out.println("Currency Type: " + accounts.currencyType);
System.out.println("Balance:" + accounts.balance);
}
public void balance(ArrayList<Customer> accounts) {
System.out.println("Balance:" + accounts.balance);
}
}
java.util.ArrayList won't have properties or methods such as customerID, accountType, currencyType and balance.
I guess your methods display() and balance() shoudn't take any arguments and should use the properties of the instance to print.
public void display()
{
System.out.println("CustomerID:" + customerID);
System.out.println("Account Type:" + accountType);
System.out.println("Currency Type: " + currencyType);
System.out.println("Balance:" + balance);
}
public void balance() {
System.out.println("Balance:" + balance);
}
Then, these lines
operation.display(accounts.get(customerID));
operation.balance(accounts.get(customerID));
should be
accounts.get(customerID).display();
accounts.get(customerID).balance();
There seems many more things to be corrected -- for example, usage of withdraw().

Creating account class in java and output

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;
}
}

Stuck on creating a object via for loop

I am stuck in creating in an object for an account, and I don't know where the problem is. My output shows only the recent inputted value. I would like to see the printed details (especially different id's) that I've created, and I don't know how to do that.
Please check my code because I think my loop has a bug in it, somewhat shows display messages that doesn't need to display.
BankSystem.java:
import java.io.*;
import java.util.Scanner;
public class BankSystem {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
BankAccount account[] = new BankAccount[5];
BankClient client[] = new BankClient[5];
BankSystem myBankSystem = new BankSystem();
String MainMenu;
do {
System.out.println("");
System.out.println("------PLP BANK SYSTEM------");
System.out.println("Main Menu: ");
System.out.println("[A]ccount Management" );
System.out.println("[C]lient Management" );
System.out.println("[Q]uit" );
System.out.println("");
System.out.print("Please select letter: ");
MainMenu = in.nextLine();
switch (MainMenu.toLowerCase()) {
case "a":
System.out.println("");
System.out.println("------PLP BANK SYSTEM------");
System.out.println("Account Management:" );
System.out.println("[N]ew Account" );
System.out.println("[A]Apply Interest to All Accounts" );
System.out.println("[L]ist All Accounts" );
System.out.println("[F]ind an Account" );
System.out.println("[D]eposit to an Account" );
System.out.println("[W]ithdraw from an Account" );
System.out.println("[R]eturn to Main Menu" );
System.out.println("");
System.out.print("Please select letter: " );
String AccountManagement = in.nextLine();
switch (AccountManagement.toLowerCase()) {
case "n": //NEW ACCOUNT
System.out.print("Please input your desired ID number: " );
int id = in.nextInt();
System.out.print("Please input your desired Balance: " );
double balance = in.nextDouble();
System.out.print("Please input your desired Interest Rate: " );
double interestRate = in.nextDouble();
// IS THE PROBLEM IS HERE ON MY LOOP?
for (int i=0; i<account.length; i++) {
account[i] = new BankAccount(id, balance, interestRate);
}
break;
case "a": //APPLY INTEREST TO ALL ACCOUNTS
System.out.println("For all accounts, compute and compound:" );
System.out.println("[M]onthly" );
System.out.println("[Q]uarterly" );
System.out.println("[A]nnually");
System.out.println("[C]ancel");
break;
case "l": //LIST ID NUMBERS OF ALL ACCOUNTS
System.out.println("List of all Accounts: ");
account[1].printDetails(); // OR THE PROBLEM IS HERE?
account[2].printDetails();
break;
case "f": //FIND ACCOUNT
System.out.println("Enter ID number: " );
break;
case "d": //DEPOSIT
System.out.println("Enter ID number: " );
System.out.println("Enter Deposit amount: " );
break;
case "w": //WITHDRAW
System.out.println("Enter ID number: " );
System.out.println("Enter Withdraw amount: " );
break;
case "r": // RETURN
break;
}
case "c":
System.out.println("");
System.out.println("------PLP BANK SYSTEM------");
System.out.println("Client Management:");
System.out.println("[N]ew Client" );
System.out.println("[L]List All Clients" );
System.out.println("[F]ind a Client" );
System.out.println("[R]eturn to Main Menu" );
System.out.println("");
System.out.print("Please select letter: " );
String ClientManagement = in.nextLine();
switch (ClientManagement.toLowerCase()) {
case "n": //NEW CLIENT
System.out.println("Enter ID number: " );
System.out.println("Please input your Name: " );
System.out.println("Please input your account ID number: " );
break;
case "l": //LIST ALL CLIENT
break;
case "f": //FIND A CLIENT
System.out.println("Enter ID number: " );
break;
case "r":
break;
default:
System.out.println("Invalid entry, Please try again!");
break;
}
default:
System.out.println("Invalid entry, Please try again!");
}
} while (!MainMenu.equals("q"));
System.out.println("Thank you for using my program!");
}
}
BankAccount.java:
public class BankAccount {
private double balance;
private double interestRate;
private int id;
public BankAccount (int id, double initialDeposit, double initialIntRate){
//Constructor
this.id=id;
this.balance=initialDeposit;
this.interestRate=initialIntRate;
}
public double getBalance(){
return balance;
}
public double getInterestRate(){
return interestRate;
}
public int getIDNumber(){
return id;
}
public void printDetails() {
System.out.println("ID Number is: " +id );
System.out.println("Current balance is: "+balance );
System.out.println("Interest rate is: "+interestRate+"%");
}
public double computeMonthlyInterest(){
interestRate=balance*interestRate;
return interestRate;
}
public void applyMonthlyInterest(){
this.balance=balance+interestRate;
}
public void applyQuarterlyInterest(){
this.balance=balance+(interestRate*3);
}
public void applyAnnualInterest(){
this.balance=balance+(interestRate*12);
}
public void deposit(double amount){
this.balance += amount;
}
public boolean withdraw (double amount) {
if (amount>balance) {
System.out.println("Withdraw amount is more than balance, Please try again.");
return false;
}
else
{
this.balance -= amount;
return true;
}
}
}
You should really consider breaking your code apart into subroutines; breaking it up will help compartmentalize the different functions.
As to your bug; I think you are saying that all accounts have the same value, and that you are not expecting that.
Your code is as follows, when creating a new account:
for (int i=0; i<account.length; i++) {
account[i] = new BankAccount(id, balance, interestRate);
}
Every time you run that line, you are replacing every element in your array with a new BankAccount object.
Your problem is that you fill the entire array of bank accounts with the latest entered bank account.
for (int i=0; i<account.length; i++) {
account[i] = new BankAccount(id, balance, interestRate);
}
Instead after receiving the information of a bank account you should just create one new BankAccount and the index of the array should be the current amount of bank accounts +1.
So make a variable to store the current amount of bank accounts, before the do statement.
int amountOfBankAccounts = 0;
And use it at the location of the for and remove the for
if(amountOfBankAccounts < 5) {
account[amountOfBankAccounts++] = new BankAccount(id, balance, interestRate);
} else {
System.out.println("Can not create a new account anymore, array is full!");
}
That should fix it. Once that works I suggest you take some time to create functions to make your code more readable and reusable.

Categories