Using Linked List as the output? - java

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().

Related

How to access an object parameter from a hashmap value

I am trying to access the accOpBalance parameter from the Account method stored in the HashMap. I want to be able to change this value based on transaction type and store it again. I also want to save the the 6 most recent transactions fot the account but not sure how to approach the problem. I hope this describes the problem well enough. Im still very new to this and would love feedback on my code aswell.
public class BankingSystem{
static int accNum;
static String accName;
static String accAdd;
static String accOpDate;
static double accOpBalance;
int option = 0;
static Scanner keyboard = new Scanner(System.in);
static HashMap<Integer, Account> accounts = new HashMap<Integer, Account>(Map.of(
accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance)
));
public BankingSystem() {
}
public static void main(String[] args) {
BankingSystem bankingSystem = new BankingSystem();
int option;
do{
option = mainMenu(keyboard);
System.out.println();
if(option == 1){
bankingSystem.createAccount(keyboard);
} else if (option == 2) {
bankingSystem.showAccounts();
} else if (option == 4) {
bankingSystem.deleteAccount();
}
}while(option != 5);
}
public void createAccount(Scanner keyboard) {
do{
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
System.out.println("-----------------------------------------------");
System.out.print("Please enter the new account number: ");
accNum = keyboard.nextInt();
newAccount.setAccNum(accNum);
System.out.print("Please enter the name of the account holder: ");
accName = keyboard.next();
newAccount.setAccName(accName);
System.out.print("Please enter the address of the account holder: ");
accAdd = keyboard.next();
newAccount.setAccAdd(accAdd);
System.out.print("Please enter the accounts open date: ");
accOpDate = keyboard.next();
newAccount.setAccOpDate(accOpDate);
System.out.print("Please enter the starting balance: ");
accOpBalance = keyboard.nextDouble();
newAccount.setAccOpBalance(accOpBalance);
accounts.put(accNum, new Account(accNum, accName, accAdd, accOpDate, accOpBalance));
}
case 2 -> {
System.out.println("Please type -1 the exit create account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public void showAccounts() {
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
}
}
public void deleteAccount(){
int key;
option = 0;
do {
System.out.println("-----------------------------------------------");
System.out.print("Please enter 1 to continue or -1 to exit: ");
option = keyboard.nextInt();
switch (option) {
case 1 -> {
System.out.print("-----------------------------------------------");
System.out.print("Please enter the Account number of the" + "\n" +
" the account you wish to delete");
System.out.print("-----------------------------------------------");
key = keyboard.nextInt();
accounts.remove(key);
}
case 2 -> {
System.out.println("Please type -1 the exit delete account menu: ");
option = keyboard.nextInt();
}
}
}while (option != -1);
}
public static int mainMenu(Scanner keyboard){
int menuOption;
System.out.println("Welcome to the bank of Cal");
System.out.println("-----------------------------------------------");
System.out.println("Main Menu" + "\n" + "Please select option:");
System.out.println("1. Create Account");
System.out.println("2. Display Accounts");
System.out.println("3. Deposit/Withdraw");
System.out.println("4. Delete Account");
System.out.println("5. Exit Program");
System.out.println("-----------------------------------------------");
do{
menuOption = keyboard.nextInt();
}while(menuOption <1 || menuOption >5);
return menuOption;
}
public class Account {
private int accNum;
private String accName;
private String accAdd;
private String accOpDate;
private double accOpBalance;
Scanner getDetails = new Scanner(System.in);
public Account(int theAccNum, String theAccName, String theAccAdd, String theAccOpDate, double theAccOpBalance){
accNum = theAccNum;
accName = theAccName;
accAdd = theAccAdd;
accOpDate = theAccOpDate;
accOpBalance = theAccOpBalance;
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public String getAccName(){
return accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public String getAccAdd(){
return accAdd;
}
public void setAccOpDate(String accOpDate){
this.accOpDate = accOpDate;
}
public String getAccOpDate(){
return accOpDate;
}
public void setAccOpBalance(double accOpBalance){
this.accOpBalance = accOpBalance;
}
public double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}

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

The else if section is not working

The else if section of deposit is not working and same is the case with else if section of no for updating the balance.
public class BankAccount
{
static double Balance;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the account holder's name...");
String Name = sc.next();
System.out.println("enter his account number...");
long AccNo = sc.nextLong();
System.out.println("enter his type of account...");
String AccTyp = sc.next();
System.out.println("enter his current balance...");
Balance = sc.nextDouble();
System.out.println("Do you want to update your balance, press y for yes and n for no...");
if(sc.next().equalsIgnoreCase("y") == true)
{
System.out.println("To withdraw money press w, To deposite the same, press d");
if(sc.next().equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(sc.next().equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else
System.out.println("Thank you for your transaction");
}
else if(sc.next().equalsIgnoreCase("n") == true)
{
System.out.println("Thank you for your transaction");
}
System.out.println("Thank you for your transaction");
}
public static double Withdraw(double a)
{
Balance = Balance - a;
return Balance;
}
public static double Deposit(double b)
{
Balance = Balance + b;
return Balance;
}
}
Don't keep invoking the next() method:
if(sc.next().equalsIgnoreCase("w") == true)
...
else if(sc.next().equalsIgnoreCase("d") == true)
Instead the code should be something like:
String response = sc.next();
if(response.equalsIgnoreCase("w"))
...
else if(response.equalsIgnoreCase("d"))
...
If 'if' block execute sc.next() then 'else' block can't execute sc.next(). Assign the input to a variable action like this.
String action=sc.next();
if(action.equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(action.equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}

method called from outside main method not executed

In the following code, the method deposit or withdraww or deposit or transfer is not being executed completely when called from main method. I am a basic java learner and this is one of my first programs. Can you please help me with the same?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Bank {
static Scanner input = new Scanner(System.in);
static String name, no;
static int accNo, accNo1, bal, amt, a, tra, acct, bal1, bala, acct2, ac1;
Bank(String name, String no, int accNo, int accNo1, int bal, int bal1, int ac1) {
this.name = name;
this.no = no;
this.accNo = accNo;
this.bal = bal;
}
private Bank(String name, String no, int accNo, int accNo1, int bal, int amt, int a, int tra, int acct, int bal1, int bala, int acct2, int ac1) {
}
static void deposit() {
System.out.println("Enter the account to which amount is to be deposited");
Scanner ac = new Scanner(System.in);
int ac1 = ac.nextInt();
System.out.println("Enter amount to deposit: (Enter in Multiples of Rs.500)");
amt = input.nextInt();
if (ac1 == accNo) {
bal = bal + amt;
System.out.println("Acct no:" + accNo);
System.out.println("Balance:Rs. " + bal);
} else if (ac1 == accNo1) {
bal1 = bal1 + amt;
System.out.println("Acct no:" + accNo1);
System.out.println("Balance:Rs. " + bal1);
} else if ((acct2 != accNo) || (acct2 != accNo1)) {
System.out.println("Account no not registered");
}
}
static void withdraw() {
System.out.println("Enter the account from which amount is to be withdrawn");
Scanner ac3 = new Scanner(System.in);
int ac2 = ac3.nextInt();
if (ac2 == accNo) {
System.out.println("Enter amount to withdraw");
amt = input.nextInt();
bal = bal - amt;
System.out.println("Acct no:" + accNo);
System.out.println("Balance:Rs. " + bal);
} else if (ac2 == accNo1) {
System.out.println("Enter amount to withdraw");
amt = input.nextInt();
bal1 = bal1 - amt;
System.out.println("Acct no:" + accNo1);
System.out.println("Balance:Rs. " + bal1);
} else {
if ((acct2 != accNo) || (acct2 != accNo1)) {
System.out.println("Account no not registered");
}
}
}
static void display() {
System.out.println("Enter the account number for balance:");
bala = input.nextInt();
if (bala == accNo) {
System.out.println("Account No:" + accNo);
System.out.println("The balance in the account is Rs." + bal);
} else if (bala == accNo1) {
System.out.println("Account No:" + accNo1);
System.out.println("The balance in the account is Rs." + bal1);
}
if ((acct2 != accNo) || (acct2 != accNo1)) {
System.out.println("Account number not registered!!");
}
}
static void transfer() {
System.out.println("Enter the account number to which amount is to be transferred:");
acct2 = input.nextInt();
if (acct2 == accNo) {
System.out.println("Enter the amount to be transferred:");
tra = input.nextInt();
if (bal < tra - 500) {
System.out.println("Insufficient funds. Minimum balance to be maintained in your account is Rs.500");
} else {
bal = bal - tra;
bal1 = bal1 + tra;
}
} else if (acct2 == accNo1) {
if (bal1 < tra - 500) {
System.out.println("Insufficient funds. Minimum balance to be maintained in your account is Rs.500");
} else {
bal1 = bal1 - tra;
bal = bal + tra;
}
} else {
if ((acct2 != accNo) || (acct2 != accNo1)) {
System.out.println("Account No not registered !!");
}
}
}
public static void main(String args[]) {
System.out.println("Welcome to personal account netbanking!");
System.out.println("To become a registered user of netbanking, kindly enter the following details");
System.out.println("Please enter your Full Name: ");
String name = input.nextLine();
System.out.println("Please enter your Contact Number:");
Scanner no1 = new Scanner(System.in);
String no = no1.nextLine();
System.out.println("Please enter the first Account Number ");
Scanner acc1 = new Scanner(System.in);
int accNo = acc1.nextInt();
System.out.println("Please enter the second Account Number ");
Scanner acc2 = new Scanner(System.in);
int accNo1 = acc1.nextInt();
System.out.println("Please enter the Amount to be deposited in the fist account");
Scanner amt1 = new Scanner(System.in);
int bal = amt1.nextInt();
System.out.println("Please enter the Amount to be deposited in the second account");
Scanner amt2 = new Scanner(System.in);
int bal1 = amt2.nextInt();
System.out.println("Thank you for registering");
System.out.println("Kindly make a note of your username: 'admin' and password: 'admin'");
System.out.println("Please enter the user name: ");
String u = input.nextLine();
System.out.println("Please enter the password: ");
BufferedReader p = new BufferedReader(new InputStreamReader(System.in));
String y = input.nextLine();
Bank b1 = new Bank(name, no, accNo, accNo1, bal, amt, a, tra, acct, bal1, bala, acct2, ac1);
if ("admin".equals(u) && "admin".equals(y)) {
int menu;
System.out.println(" Welcome " + name);
boolean quit = false;
do {
System.out.println("Please enter your choice: ");
System.out.println("1. Balance Enquiry");
System.out.println("2. Deposit Amount");
System.out.println("3. Withdraw Amount ");
System.out.println("4. Transfer Amount");
System.out.println("5. Exit");
menu = input.nextInt();
switch (menu) {
case 1:
b1.display();
break;
case 2:
b1.deposit();
break;
case 3:
b1.withdraw();
break;
case 4:
b1.transfer();
break;
case 5:
quit = true;
break;
}
} while (!quit);
} else {
System.out.println("Invalid username or password");
}
}
}
The problem is that you have two constructors and when you call "new Bank", the empty constructor is called. Copy the assignments from the first constructor into the second or just call the good constructor from the empty one.
Edit:
You have this:
Bank(String name, String no, int accNo, int accNo1, int bal, int bal1, int ac1) {
this.name = name;
this.no = no;
this.accNo = accNo;
this.bal = bal;
}
private Bank(String name, String no, int accNo, int accNo1, int bal, int amt, int a, int tra, int acct, int bal1, int bala, int acct2, int ac1) {
}
And you should have (at least) this:
Bank(String name, String no, int accNo, int accNo1, int bal, int bal1, int ac1) {
this.name = name;
this.no = no;
this.accNo = accNo;
this.bal = bal;
}
private Bank(String name, String no, int accNo, int accNo1, int bal, int amt, int a, int tra, int acct, int bal1, int bala, int acct2, int ac1) {
this.name = name;
this.no = no;
this.accNo = accNo;
this.bal = bal;
}
I'm guessing your problem is that the code is throwing an exception somewhere and that's it's only partially running. Try (no pun intended) putting a try catch block around your code:
public static main(String args[]) {
try {
// you existing code goes here
} catch (Throwable t) {
System.out.println(t);
}
}
This will at least tell you what the problem is.

Creating a Bank program [closed]

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

Categories