Compte Bancaire Programme Java


Je crée un programme de compte bancaire pour ma classe java qui est supposé gérer jusqu'à 5 comptes bancaires différents. Le programme doit permettre la création d'un nouveau compte, ce que j'ai fait, permettre le dépôt et le retrait, ce qui est également fait, les 2 parties que je ne peux pas travailler sont 1: la banque ne peut avoir jusqu'à 5 comptes, donc si un 6ème essaie d'être créé, un message apparaît disant que 5 sont déjà créés, et 2: l'une des options doit imprimer tous les soldes du compte courant les comptes en banque.

C'est mon code à partir de maintenant:

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 account balance");
        System.out.println("5) Quit");
        System.out.println();
        System.out.print("Enter choice [1-5]: ");
        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("Here are the balances " + "for each account:");
            case 6:
                System.exit(0);
        }
}
while (user_choice != '6');
}

static class Bank {
private BankAccount[] accounts;     // all the bank accounts at this bank
private int numOfAccounts = 5;      // the number of bank accounts at this bank

// Constructor: A new Bank object initially doesn’t contain any accounts.
public Bank() {
    accounts = new BankAccount[5];
    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 printAccountInfo(int accountNum, int n) {
    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.");
    }

}





  static class BankAccount{

       private int accountNum;
       private String customerName;
       private double balance;
       private  static int noOfAccounts=0;

       public String getAccountInfo(){
           return "Account number: " + accountNum + "\nCustomer Name: " + customerName + "\nBalance:" + balance +"\n";
       }


       public BankAccount(String abc, double xyz){
         customerName = abc;
         balance = xyz;
         noOfAccounts ++;
         accountNum = noOfAccounts;
       }

    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;

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

            }
        }
    }

}//end of class

Le programme fonctionne bien, j'ai juste besoin d'ajouter ces deux options, et je ne peux pas les faire fonctionner correctement, comment ferais-je pour faire cela? De plus, les options 3 et 4 ne devraient pas fonctionner si aucun compte n'a encore été créé. Merci à l'avance.

MISE À JOUR: c'est ce que j'ai essayé, je continue à obtenir une erreur de type int de cette méthode.

public int openNewAccount(String customerName, double openingBalance) {
    if(numOfAccounts > 5)
    {
        System.out.println("5 accounts already exist");
    }
    else
    {
    BankAccount b = new BankAccount(customerName, openingBalance);
    accounts[numOfAccounts] = b;
    numOfAccounts++;
    return b.getAccountNum();
    }
}

MISE À JOUR 2: J'ai ajouté une instruction return, maintenant quand elle s'exécute, elle s'ouvrira comptes jusqu'au numéro 5, mais pour chaque compte après le numéro 5, il indique simplement que le numéro de compte est à nouveau 5 au lieu de ne pas ouvrir de compte.

public int openNewAccount(String customerName, double openingBalance) {
    if(numOfAccounts > 5)
    {
        System.out.println("5 accounts already exist");
    }
    else
    {
    BankAccount b = new BankAccount(customerName, openingBalance);
    accounts[numOfAccounts] = b;
    numOfAccounts++;
    return b.getAccountNum();
    }
    return numOfAccounts;
}
Author: Will, 2015-05-06

3 answers

C'est assez simple. Créez une liste de taille 5 et ajoutez le compte dans cette liste lorsque l'utilisateur en crée un. Avant d'ajouter, vérifiez simplement si la taille de la liste

Pour l'option 2, parcourez simplement la liste et affichez les résultats

 1
Author: HJK, 2015-05-06 03:22:34

1; dans la méthode du compte openNewBank; avant de créer le nouveau compte bancaire et d'augmenter le nombre de 1; vérifiez si le nombre de compte est déjà à 5 ou plus et s'il est ne créez pas le compte et n'augmentez pas le nombre.

2: Parcourez le nombre de variables de compte et imprimez.

 1
Author: Asura, 2015-05-06 03:23:06

J'y ai ajouté un système de mot de passe. et agréable à regarder compte num. Code:

import java.io.*;
import java.util.Random;
public class Computer_Bank_of_India {
public static int NewRandom(int min, int max) {
    Random rand = new Random();
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}
public static void main(String args[])throws IOException, InterruptedException {
    InputStreamReader ir = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(ir);
    Bank myBank = new Bank();
    int Option = 1, Account_Number, Account_Password, atempts = 0, Pass;
    String Name;
    double Balance, Money;
    System.out.println("Please wait, the system is starting...");
    while(Option !=5) {
        Thread.sleep(4000);
        System.out.println("1) Open a new bank account");
        Thread.sleep(250);
        System.out.println("2) Deposit to a bank account");
        Thread.sleep(250);
        System.out.println("3) Withdraw to bank account");
        Thread.sleep(250);
        System.out.println("4) Print the detailed account information including last transactions");
        Thread.sleep(250);
        System.out.println("5) Quit");       
        System.out.println();      
        System.out.print("                       Enter Option [1-5]: ");
        Option = Integer.parseInt(br.readLine());
        switch(Option) {
            case 1 : System.out.println("Enter a customer name :");
                     Name = br.readLine();
                     System.out.println("Enter a opening balance :");
                     Balance = Double.parseDouble(br.readLine());
                     Thread.sleep(250);
                     System.out.println("Creating your account....");
                     Thread.sleep(500);
                     int[] arrDetails= myBank.AddNewAccount(Name, Balance);                     
                     System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);
                     break;
            case 2 : System.out.println("Enter a account number :");
                     Account_Number = Integer.parseInt(br.readLine());
                     System.out.println("Enter a account password :");
                     Account_Password = Integer.parseInt(br.readLine());
                     System.out.println("Enter a deposit amount :");
                     Money = Double.parseDouble(br.readLine());
                     myBank.Deposit(Account_Number, Account_Password, Money);
                     break;
            case 3 : System.out.println("Enter a account number :");
                     Account_Number = Integer.parseInt(br.readLine());
                     System.out.println("Enter a account password :");
                     Account_Password = Integer.parseInt(br.readLine());
                     System.out.println("Enter a deposit amount :");
                     Money = Double.parseDouble(br.readLine());
                     myBank.Withdraw(Account_Number, Account_Password, Money);
                     break;
            case 4 : System.out.println("Enter a account number :");
                     Account_Number = Integer.parseInt(br.readLine());
                     System.out.println("Enter a account password :");
                     Account_Password = Integer.parseInt(br.readLine());
                     myBank.Transactions(Account_Number, Account_Password);
                     break;
            case 5 : System.out.println("Please Enter your password :");
                     Pass = Integer.parseInt(br.readLine());
                     if(Pass == myBank.Password) {
                         System.out.println("                       System shutting down.....");
                         Option = 5;
                         break;
                     } 
                     else {
                         Thread.sleep(250);
                         System.out.println("You have enter a wrong password. Please try again");
                         Option = 0;
                     }
            default: System.out.println("Invalid option. Please try again.");
        }
    }
}
static class Bank {
    private int Password=2684;
    private BankAccount[] accounts;
    private int numOfAccounts;
    public Bank() {
        accounts = new BankAccount[100];
        numOfAccounts = 0;
    }
    public int [] AddNewAccount(String Name, Double Balance) {
        BankAccount b = new BankAccount(Name, Balance);
        accounts[numOfAccounts] = b;
        numOfAccounts++;
        int Acc = b.getAccountNum()[0];
        int Pass = b.getAccountNum()[1];
        int[]details = {Acc, Pass};
        return details;
    }
    public void Withdraw(int Account_Number, int pass, double Money) {
        for (int i =0; i<numOfAccounts; i++) {     
            int a = accounts[i].getAccountNum()[0];
            if (Account_Number == a) {
                int p = accounts[i].getAccountNum()[1];
                if( pass == p) {
                    accounts[i].withdraw(Money);
                    return;
                }
            }   
        }  
        System.out.println("                       You have entered a wrong Account number or Password.");
    }
    public void Deposit(int Account_Number, int pass, double Money) {  
        for (int i =0; i<numOfAccounts; i++) {     
            int a = accounts[i].getAccountNum()[0];
            if (Account_Number == a) {
                int p = accounts[i].getAccountNum()[1];
                if( pass == p) {
                    accounts[i].deposit(Money);
                    return;   
                }
            }   
        }  
        System.out.println("                       You have entered a wrong Account number or Password.");
    }
    public void Transactions(int Account_Number, int pass) {
        for(int i = 0;i<numOfAccounts; i++) {
            int a = accounts[i].getAccountNum()[0];
            if (Account_Number ==  a ) {
                int p = accounts[i].getAccountNum()[1];
                if( pass == p) {
                    System.out.println(accounts[i].getAccountInfo());
                    System.out.println("                        Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
                    return;
                }
            }
        }
        System.out.println("                       You have entered a wrong Account number or Password.");
    }
}
static class BankAccount{
    private int User_Password;
    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 + "\n                        Customer Name: " + customerName + "\n                        Balance:" + balance +"\n";
    }
    public String getTransactionInfo(int n) {
        String transaction = transactionsSummary[n];
        return transaction;
        }
    public BankAccount(String abc, double xyz){        
        customerName = abc;        
        balance = xyz;        
        noOfAccounts ++;
        User_Password = NewRandom(1000, 9999);
        accountNum = NewRandom(800000000, 999999999);       
        transactions = new double[100];                         
        transactionsSummary = new String[100];               
        transactions[0] = balance;                      
        transactionsSummary[0] = "A balance of : Rs" + Double.toString(balance) + " was deposited.";       
        numOfTransactions = 1;             
    }
    public int [] getAccountNum(){
        int account = accountNum;
        int Pass = User_Password;
        int [] details = {account, Pass};
        return details;
    }
    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] = "Rs." + Double.toString(amount) + " was deposited.";            
            numOfTransactions++;
            System.out.println("                       Amount deposited successfully");
        }         
    }
    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] = "Rs." + Double.toString(amount) + " was withdrawn.";
                numOfTransactions++;
                System.out.println("                       Amount Withdrawn successfully");
            }
        }
    }
}
}
 0
Author: Abhigyan Singh, 2016-04-01 14:31:40