Stuck on creating a object via for loop - java

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.

Related

Basic Menu with Cases

I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.

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.

how can i update balance after doing withdrawal and deposits(withdraw,deposit,balance inquiry) java

I have a homework in java. I am tasked to build a bank that can withdraw, deposit and inquire balance. My problem is that I couldn't get to update my balance after deposits and withdrawals... I've tried everything I could do but still cant get the logic. Can someone help add to my program... thanks
import java.util.Scanner;
public class bankJava
{
Scanner input = new Scanner(System.in);
double balance;
double amount;
public void withdraw()
{
System.out.println("Enter amount: ");
amount = input.nextInt();
balance = balance - amount;
}
public void deposit()
{
System.out.println("Enter amount: ");
amount = input.nextInt();
balance = balance + amount;
}
public void accBalance()
{
}
}
---------------------------------MAIN--------------------------------
import java.util.Scanner;
public class bankJavaTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int action;
bankJava wdraw = new bankJava();
bankJava dposit = new bankJava();
bankJava balanceInquiry = new bankJava();
bankJava amount = new bankJava();
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
wdraw.withdraw();
System.out.println("***************************");
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
dposit.deposit();
System.out.println("***************************");
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
balanceInquiry.accBalance();
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Why you are instatiating 4 different JavaBank? Doing this for each operation you will execute each method in a different object. If I understand well your question I think you could resolve your problem easily working in the same object.
import java.util.Scanner;
public class bankJavaTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int action;
bankJava myJavaBank = new bankJava(); //creating the bank
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
myJavaBank.withdraw(); //withdrawing from it
System.out.println("***************************");
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
myJavaBank.deposit(); //deposit from it
System.out.println("***************************");
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
myJavaBank.accBalance();
//You don't post this method but I suppose it will refer to the same bank
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Now should work. With your code you had 4 different bank, one only for deposit, one only for withdraw and so on. So one bank will continue to increase money, and one continue to decrease in negative.
Morover the amount parameter should not be a JavaBank parameter, bur a local variable inside each method so that it does not define a Bank.
Something like
public class bankJava
{
Scanner input = new Scanner(System.in);
double balance;
public void withdraw()
{
System.out.println("Enter amount: ");
double amount = input.nextInt();
balance = balance - amount;
}
public void deposit()
{
System.out.println("Enter amount: ");
double amount = input.nextInt();
balance = balance + amount;
}
I also suggest to change the input.nextInt() with input.nextDouble() so that you create the amount as a double.
If you don't see the Balance Inquiry is because obviously you have the accBalance() method blank. Edit it like this:
public void accBalance(){
System.out.println("Your balance is: "+this.balance);
}
import java.util.Scanner;
public class BankJava {
double balance = 0;
double amount;
public void withdraw(int amount) {
balance = balance - amount;
}
public void deposit(int amount) {
balance = balance + amount;
}
public double showBalance() {
return balance;
}
public static void main(String[] args) {
BankJava bank = new BankJava();
Scanner input = new Scanner(System.in);
int action;
int amount;
do{
System.out.println("Choose Action: ");
System.out.println("(1) Withdraw");
System.out.println("(2) Deposit");
System.out.println("(3) Balance Inquiry");
System.out.println("(4) Exit");
action = input.nextInt();
switch(action){
//---------WITHDRAW------------//
case 1 :
System.out.println("******Withdraw******");
System.out.println("enter amount:");
amount = input.nextInt();
bank.withdraw(amount);
System.out.println("***************************");
System.out.println("Your balance is now: " + bank.showBalance());
break;
//---------DEPOSIT------------//
case 2 :
System.out.println("******Deposit******");
System.out.println("enter amount:");
amount = input.nextInt();
bank.deposit(amount);
System.out.println("***************************");
System.out.println("Your balance is now: " + bank.showBalance());
break;
//-----------Balance Inquiry-------//
case 3 :
System.out.println("******Balance Inquiry******");
System.out.println("Your balance is: " + bank.showBalance());
System.out.println("***************************");
break;
case 4 :
System.out.println("Thank you for choosing our bank!");
break;
default :
System.out.println("Invalid action.");
break;
}
}while(action != 4);
}
}
Try this code, compare with yours and figure out whats wrong, also you can ask me if you need more help

Error: Non-static variable inout cannot be referenced from a static context

I am working on a program for my CS class that involves methods and variables. I know it's a problem with the scope, or at least I think, but not sure how to solve. I can't use objects. The code isn't complete yet, because I'm currently just focused on this one problem.
import java.util.Scanner;
public class MethodBankingSystem {
Scanner input = new Scanner(System.in);
public static double Deposit(double userDeposit, double userBalance) {
System.out.print("Enter the amount you would like to deposit: ");
userDeposit = input.nextDouble(); //Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; //Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n",userBalance );
return userBalance;
}
public static double Withdraw(double userWithdraw, double userBalance) {
System.out.print("Enter the amount you would like to withdraw: ");
userWithdraw = input.nextDouble(); //Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { //Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
}
else {
userBalance = userBalance - userWithdraw; //Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n",userBalance );
}
return userBalance;
}
public static void CurrentBalance(double userBalance) {
System.out.printf("Current balance is $" + "%.2f \n\n",userBalance );
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double userBalance = 100.00;
double userDeposit;
double userWithdraw;
double userInput;
String cardNumber;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n1 - Make a Deposit\n" +
"2 - Make a Withdraw\n3 - Check your Current Balance\n9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextDouble();
switch (userInput) {
case '1':
Deposit(userDeposit, userBalance);
break;
case '2':
Withdraw(userWithdraw, userBalance);
break;
case '3':
CurrentBalance(userBalance);
break;
case '4':
CurrentBalance(userBalance);
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput !=9);
}
}
Basically the problem is this:
static means that there is only one instance of that field per class (not instance). The field is essentially shared between all instances; modifying it in one instance will affect it in all instances. You can reference static fields within instances but you cannot statically reference instance members.
Either make input static (not really recommended):
static Scanner input = new Scanner(System.in);
Or make an instance of MethodBankingSystem and remove the static modifiers from your methods (this is what I think you are trying to do):
import java.util.Scanner;
public class MethodBankingSystem {
Scanner input = new Scanner(System.in);
public double Deposit(double userDeposit, double userBalance) {
System.out.print("Enter the amount you would like to deposit: ");
userDeposit = input.nextDouble(); //Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; //Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n",userBalance );
return userBalance;
}
public double Withdraw(double userWithdraw, double userBalance) {
System.out.print("Enter the amount you would like to withdraw: ");
userWithdraw = input.nextDouble(); //Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { //Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
}
else {
userBalance = userBalance - userWithdraw; //Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n",userBalance );
}
return userBalance;
}
public void CurrentBalance(double userBalance) {
System.out.printf("Current balance is $" + "%.2f \n\n",userBalance );
}
public static void main(String[] args) {
new MethodBankingSystem();
}
MethodBankingSystem () {
Scanner input = new Scanner(System.in);
double userBalance = 100.00;
double userDeposit;
double userWithdraw;
double userInput;
String cardNumber;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n1 - Make a Deposit\n" +
"2 - Make a Withdraw\n3 - Check your Current Balance\n9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextDouble();
switch (userInput) {
case '1':
Deposit(userDeposit, userBalance);
break;
case '2':
Withdraw(userWithdraw, userBalance);
break;
case '3':
CurrentBalance(userBalance);
break;
case '4':
CurrentBalance(userBalance);
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput !=9);
}
}
I FIXED YOUR CODE GET IT BEFORE THE QUESTION GETS DELETED
Because I'm a nice guy I fixed your code. There were all sorts of issues, please read up on them. You create an instance of input twice, you are switching on a double you are calling Deposit(userDeposit, userBalance); without initialisinguserDeposit, you declare cardNumber but never instantiate or even try to use it anywhere, you have issues with static scoping.
import java.util.Scanner;
public class MethodBankingSystem {
public static void main(String[] args) {
new MethodBankingSystem();
}
Scanner input;
double userBalance = 100.00;
MethodBankingSystem() {
input = new Scanner(System.in);
int userInput;
String menu = "Welcome to Mustang Bank\nPlease choose from the options below:\n" + "1 - Make a Deposit\n"
+ "2 - Make a Withdraw\n" + "3 - Check your Current Balance\n"
+ "9 - Exit the Program\nEnter Option:\n";
do {
System.out.print(menu);
userInput = input.nextInt();
switch (userInput) {
case 1:
Deposit();
break;
case 2:
Withdraw();
break;
case 3:
CurrentBalance();
break;
case 9:
break;
default:
System.out.println("This option is not acceptable.");
}
} while (userInput != 9);
input.close();
}
public double Deposit() {
System.out.print("Enter the amount you would like to deposit: ");
double userDeposit = input.nextDouble(); // Create variable userDeposit for amount entered
userBalance = userBalance + userDeposit; // Replace value for userBalance
System.out.printf("New balance after deposit is: $" + "%.2f \n\n", userBalance);
return userBalance;
}
public double Withdraw() {
System.out.print("Enter the amount you would like to withdraw: ");
double userWithdraw = input.nextDouble(); // Create variable userWithdraw for amount entered
if (userWithdraw > userBalance) { // Create if/else statement to make sure enough funds are available
System.out.printf("Funds are not available for this withdraw \n\n");
} else {
userBalance = userBalance - userWithdraw; // Replace value for userBalance
System.out.printf("New balance after withdraw is: $" + "%.2f \n\n", userBalance);
}
return userBalance;
}
public void CurrentBalance() {
System.out.printf("Current balance is $" + "%.2f \n\n", userBalance);
}
}

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