Arrays and bank accounts in Java - java

I am trying to write a simple Bank Account Management program that does the following:
Creates a new account with Account number and Balance taken from user and stored in an array
Selects an account (from the array)
Deletes the account selected
Withdraw and Deposit into account selected.
Problem: I don't understand what the my mistakes are.
I tried using different types of arrays for account number and balance storing, but I didn't not find the answer yet. I search the web and Stackoverflow for references, documentations, simple examples, but could not find any (the ones that I found, use some commands and things that I haven't learned yet so I can understand how they work). I am a beginner, I am still learning and would appreciate some advice. Thanks!
//Bank account class
public class account {
private int ANumber;
private double balance;
public account(double initialBalance, int accno) {
balance = initialBalance;
ANumber = accno;
}
public void deposit (double u_amm){
balance += u_amm;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccount(){
return ANumber;
}
}
And this is the Main class
import java.util.Scanner;
// main class
public class bankmain {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
//Options
while(true){
if(choice == "ne"){
int nacc;
int bal;
int [][]array = new int[nacc][bal]; // Array for account and balance
System.out.print("Insert account number: ");
nacc =input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
bal=input.nextInt(); //-- Input nr for array insertion
System.out.println("Current account: " + nacc + " " + "Balance " + bal);
break;
}
// account selection
if(choice.equals("se")){
System.out.println("Enter number of account to be selected: ");
//user input for account nr from array
System.out.println("Account closed.");
}
//close account
if(choice.equals("de")){
//array selected for closing
System.out.println("Account closed.");
}
// deposit
if(choice.equals("dp")){
System.out.print("Enter amount to deposit: ");
double amount = scan.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
System.out.println("You have deposited " + (amount + account.getBalance()));
}
}
// withdrawal
if(choice.equals("wi")){
System.out.print("Enter amount to be withdrawn: ");
double amount = scan.nextDouble();
if (amount > account.balance()){
System.out.println("You can't withdraw that amount!");
} else if (amount <= account.balance()) {
account.withdraw(amount);
System.out.println("NewBalance = " + account.getBalance());
}
}
//quit
if(choice == "ex"){
System.exit(0);
}
} // end of menu loop
}// end of main
} // end of class

Your code was wrong on many levels - first try to work on your formatting and naming conventions so you don't learn bad habbits. Dont use small leters for naming classes, try to use full words to describe variables and fields, like in that Account.class example:
public class Account {
private Integer accountNumber;
private Double balance;
public Account(final Integer accountNumber, final Double initialBalance) {
this.accountNumber = accountNumber;
balance = initialBalance;
}
public Double deposit (double depositAmmount) {
balance += depositAmmount;
return balance;
}
public Double withdraw(double withdrawAmmount) {
balance -= withdrawAmmount;
return balance;
}
public Double getBalance() {
return balance;
}
public Integer getAccountNumber() {
return accountNumber;
}
}
Also try to use the same formatting(ie. spaces after brackets) in all code, so that it's simpler for you to read.
Now - what was wrong in your app:
Define the proper holder for your accounts i.e. HashMap that will hold the information about all accounts and will be able to find them by accountNumber.
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();
This one should be inside your while loop, as you want your user to do multiple tasks. You could ommit the println's but then the user would have to go back to the top of the screen to see the options.
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.nextLine();
System.out.println("Your choice: " + choice);
You shouldn't compare Strings using '==' operator as it may not return expected value. Take a look at: How do I compare strings in Java? or What is the difference between == vs equals() in Java?. For safty use Objects equals instead, ie:
choice.equals("ne")
There was no place where you created the account:
Account newAccount = new Account(newAccountNumber, initialBalance);
You didn't use if-else, just if's. It should look more like that (why to check if the choice is 'wi' if it was already found to be 'ne'):
if(choice.equals("ne")) {
//doStuff
} else if choice.equals("se") {
//doStuff
} //and so on.
If your using Java version >= 7 then instead of if-else you can use switch to compare Strings.
There was no notification of the wrong option:
} else {
System.out.println("Wrong option chosen.");
}
You didn't close your Scanner object. This really doesn't matter here, as it's in main method and will close with it, but it's a matter of good habbits to always close your streams, data sources etc when done using it:
input.close();
So the whole code can look like this:
import java.util.HashMap;
import java.util.Scanner;
// main class
public class BankAccount {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
HashMap<Integer, Account> accountMap = new HashMap<Integer, Account>();
//Options
while(true) {
System.out.println("Enter the option for the operation you need:");
System.out.println("****************************************************");
System.out.println("[ Options: ne - New Account de - Delete Account ]");
System.out.println("[ dp - Deposit wi - Withdraw ]");
System.out.println("[ se - Select Account ex - Quit ]");
System.out.println("****************************************************");
System.out.print("> "); //indicator for user input
String choice = input.next();
System.out.println("Your choice: " + choice);
if(choice.equals("ne")) {
Integer newAccountNumber;
Double initialBalance;
Account newAccount;
// Array for account and balance
System.out.print("Insert account number: ");
newAccountNumber = input.nextInt(); //-- Input nr for array insertion
System.out.print("Enter initial balance: ");
initialBalance=input.nextDouble(); //-- Input nr for array insertion
newAccount = new Account(newAccountNumber, initialBalance);
accountMap.put(newAccountNumber, newAccount);
System.out.println("New Account " + newAccountNumber + " created with balance: " + initialBalance);
}
//select account
else if(choice.equals("se")) {
System.out.println("Enter number of account to be selected: ");
Integer accountToGetNumber = input.nextInt();
Account returnedAccount = accountMap.get(accountToGetNumber);
if (returnedAccount != null)
{
System.out.println("Account open. Current balance: " + returnedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
//close account
else if(choice.equals("de"))
{
System.out.println("Enter number of account to be selected: ");
Integer accountToDeleteNumber = input.nextInt();
Account removedAccount = accountMap.remove(accountToDeleteNumber);
if (removedAccount != null)
{
System.out.println("Account " + removedAccount.getAccountNumber() + " has been closed with balance: " + removedAccount.getBalance());
}
else
{
//user input for account nr from array
System.out.println("Account does not exist.");
}
}
// deposit
else if(choice.equals("dp")) {
System.out.println("Enter number of account to deposit: ");
Integer accountToDeposit = input.nextInt();
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
if(amount <= 0){
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToDeposit).deposit(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToDeposit).getBalance());
}
}
// withdrawal
else if(choice.equals("wi")) {
System.out.println("Enter number of account to withdraw: ");
Integer accountToWithdraw = input.nextInt();
System.out.print("Enter amount to withdraw: ");
double amount = input.nextDouble();
if(amount <= 0) {
System.out.println("You must deposit an amount greater than 0.");
} else {
accountMap.get(accountToWithdraw).withdraw(amount);
System.out.println("You have deposited " + (amount));
System.out.println("Current balance " + accountMap.get(accountToWithdraw).getBalance());
}
}
//quit
else if(choice.equals("ex")) {
break;
} else {
System.out.println("Wrong option.");
} //end of if
} //end of loop
input.close();
} //end of main
} //end of class
There still is much to improve, i.e. input validation - but this should work for the begining.

You have written the above code, but it has many mistakes. You need to learn the The basics of Java programming.
I have modified your program to perform below operations :-
Create new account.
Select existing account.
Deposit amount.
Withdraw amount.
View balance.
Delete account.
Exit.
Account.java :
/**
* This class performs bank operations
*/
public class Account {
private int accNumber;
private double balance;
public Account(double initialBalance, int accNo) {
balance = initialBalance;
accNumber = accNo;
}
public void deposit(double amount) {
balance += amount;
}
public double withdraw(double amount) {
balance -= amount;
return amount;
}
public double getBalance() {
return balance;
}
public int getAccNumber() {
return accNumber;
}
}
BankMain.java :
public class BankMain {
private static double amount;
private static ArrayList<Account> accountList = new ArrayList<>();
private static Account selectedAccount;
private static boolean flag = false;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Menu starts from here
Scanner input = new Scanner(System.in);
System.out.println("Enter the option for the operation you need:");
System.out
.println("****************************************************");
System.out
.println("[ Options: new - New Account del - Delete Account ]");
System.out
.println("[ dp - Deposit wi - Withdraw bal - Check balance ]");
System.out
.println("[ se - Select Account exit - Quit ]");
System.out
.println("****************************************************");
Account account = null;
while (true) {
System.out.println("> "); // indicator for user input
String choice = input.next();
// Options
switch (choice) {
case "new":
// Create new account
int accNo = 0;
int bal = 0;
System.out.println("Enter account number : ");
accNo = input.nextInt();
System.out.println("Enter initial balance: ");
bal = input.nextInt();
System.out.println("Current account: " + accNo + " "
+ "Balance " + bal);
account = new Account(bal, accNo);
accountList.add(account);
break;
case "se":
// select account
System.out
.println("Enter account number for further operations : ");
int selectedAcc = scan.nextInt();
System.out.println("Selected account : " + selectedAcc);
for (Object object : accountList) {
selectedAccount = (Account) object;
if (selectedAccount.getAccNumber() == selectedAcc) {
flag = true;
break;
} else {
flag = false;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
if (accountList.size() == 0) {
System.out.println("Zero account exists.");
}
break;
case "del":
// close account
System.out
.println("Enter account number for further operations : ");
int selectedAcc1 = scan.nextInt();
System.out.println("Selected account : " + selectedAcc1);
Iterator<Account> iterator = accountList.iterator();
while (iterator.hasNext()) {
selectedAccount = (Account) iterator.next();
if (selectedAccount.getAccNumber() == selectedAcc1) {
iterator.remove();
flag = true;
break;
}
}
if (!flag) {
System.out.println("Account doesn't exists.");
}
System.out.println("Account " + selectedAcc1 + " closed.");
break;
case "dp":
// Deposit amount
System.out.println("Enter amount to deposit : ");
amount = scan.nextDouble();
if (amount <= 0) {
System.out
.println("You must deposit an amount greater than 0.");
} else {
if (flag) {
selectedAccount.deposit(amount);
System.out.println("You have deposited " + amount
+ ". Total balance : "
+ (selectedAccount.getBalance()));
} else {
System.out.println("Please select account number.");
}
}
break;
case "wi":
// Withdraw amount
System.out.println("Enter amount to be withdrawn: ");
amount = scan.nextDouble();
if (amount > account.getBalance() && amount <= 0) {
System.out.println("You can't withdraw that amount!");
} else if (amount <= selectedAccount.getBalance()) {
if (flag) {
selectedAccount.withdraw(amount);
System.out.println("You have withdraw : " + amount
+ " NewBalance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
}
break;
case "bal":
// check balance in selected account
if (flag) {
System.out.println("Your current account balance : "
+ selectedAccount.getBalance());
} else {
System.out.println("Please select account number.");
}
break;
case "exit":
default:
// quit
System.out.println("Thank You. Visit Again!");
flag = false;
input.close();
scan.close();
System.exit(0);
break;
}
} // end of menu loop
}// end of main
} // end of class
I have tested this code & it is working fine.
Output :
Enter the option for the operation you need:
****************************************************
[ Options: new - New Account del - Delete Account ]
[ dp - Deposit wi - Withdraw bal - Check balance ]
[ se - Select Account exit - Quit ]
****************************************************
> new
Enter account number : 101
Enter initial balance: 10000
Current account: 101 Balance 10000
> new
Enter account number : 102
Enter initial balance: 25000
Current account: 102 Balance 25000
> se
Enter account number for further operations : 103
Selected account : 103
Account doesn't exists.
> se
Enter account number for further operations : 101
Selected account : 101
> bal
Your current account balance : 10000.0
> dp
Enter amount to deposit : 2500
You have deposited 2500.0. Total balance : 12500.0
> wi
Enter amount to be withdrawn: 500
You have withdraw : 500.0 NewBalance : 12000.0
> se
Enter account number for further operations : 102
Selected account : 102
> bal
Your current account balance : 25000.0
> del
Enter account number for further operations : 101
Selected account : 101
Account 101 closed.
> se
Enter account number for further operations : 101
Selected account : 101
Account doesn't exists.
> exit
Thank You. Visit Again!

Related

ATM method program (possible logic or bracket errors)

So, I have to make a program that acts as a basic ATM and I've encountered 2 problems:
When I test the program for invalid passwords with a related account, the program is supposed to do a loop count that gives the user a max of 3 invalid attempts before it kicks the user out but instead it prints "Invalid password" 3 times and ends the program after the first wrong password. I believe this one is a bracketing error but I'm not actually sure myself
AND
Whenever I run an operation like depositing money into the account, the program will display the new amount but it won't actually store the new value for the program. For example if I deposit $100 into account 1, it will say the new balance is $620.36, but when it loops back to the main menu and I check the new balance again and it reverts it back to the previous value, which it's not supposed to (tjis is where I think the logic error might be)
I was hoping for someone to be able to guide me in the right direction for either possible debugging solutions or a general solution of my error in coding.
This is the code:
import java.util.*;
public class ATM {
public static Scanner kbd;
private static final int MAXATTEMPTS = 3;
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("Hello, user. This is an ATM.");
System.out.println("Please enter account number");
String acctNum = kbd.next();
System.out.println("Please enter password");
String pwd = kbd.next();
int attemptNumber = 0;
String res = checkID(acctNum, pwd);
do{
if (res.equals("error")){
attemptNumber++;
System.out.println("Invalid password, please try again.");
if (attemptNumber == MAXATTEMPTS){
System.out.print("Maximum Login Attempts Reached.");
System.exit(0);
}
}
else {
double balance = Double.parseDouble(res);
while(true){
int option = menu();
switch (option) {
case 1:
displayBalance(balance);
break;
case 2:
deposit(balance, balance);
break;
case 3:
withdraw(balance, balance);
break;
case 4:
System.out.println("Thank you for banking with us, have a nice day!");
System.exit(0);
}
}
}
}
while (res.equals("error"));
kbd.close();
}
/**
* Determines if acctNum is a valid account number and pwd is the
* correct password for the account.
* #param acctNum The account number to be tested
* #param pwd The possible password for the account
* #return If the account information is valid, returns the account balance
* as a string. If the account information is invalid, returns the string "error".
*/
public static String checkID(String acctNum, String pwd)
{
String result = "error";
// Strings a, b, and c contain the valid account numbers and passwords.
// For each string, the account number is listed first, followed by
// a space, followed by the password for the account, followed by a space,
// followed by the current balance.
String a = "44567-5 mypassword 520.36";
String b = "1234567-6 anotherpassword 48.20";
String c = "4321-0 betterpassword 96.74";
String acctNum1, acctNum2, acctNum3, pwd1, pwd2, pwd3, bal1, bal2, bal3;
acctNum1 = a.substring(0, a.indexOf(" "));
acctNum2 = b.substring(0, a.indexOf(" "));
acctNum3 = c.substring(0, a.indexOf(" "));
pwd1 = a.substring(a.indexOf(" ")+1, a.lastIndexOf(" "));
pwd2 = b.substring(b.indexOf(" ")+1, b.lastIndexOf(" "));
pwd3 = c.substring(c.indexOf(" ")+1, c.lastIndexOf(" "));
bal1 = a.substring(a.lastIndexOf(" " )+1);
bal2 = b.substring(a.lastIndexOf(" " )+1);
bal3 = c.substring(a.lastIndexOf(" " )+1);
if (acctNum.equals(acctNum1) && pwd.equals(pwd1)){
result = bal1;
}
if (acctNum.equals(acctNum2) && pwd.equals(pwd2)){
result = bal2;
}
if (acctNum.equals(acctNum3) && pwd.equals(pwd3)){
result = bal3;
}
return result;
}
/**
*/
public static int menu(){
boolean invalidInput = true;
do {
System.out.println("Please select from the following options:");
System.out.printf("1. Display Balance \n");
System.out.printf("2. Deposit \n");
System.out.printf("3. Withdraw \n");
System.out.printf("4. Log Out \n");
int choice = kbd.nextInt();
if (choice == 1){
return 1;
}
else {
if (choice == 2){
return 2;
}
else{
if (choice == 3){
return 3;
}
if (choice == 4) {
return 4;
}
}
}
}
while(invalidInput);
return 0;
}
/**
*
* #param accBalance given account balance for Account
* #param depoAmnt amount going to be added to accBalance
* #return double that will show updated balance
*/
public static double deposit(double accBalance, double depoAmnt){
System.out.println("How much would you like to deposit");
depoAmnt = kbd.nextDouble();
double newBalance = accBalance + depoAmnt;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
/**
*
* #param accBalance amount of money in account
* #return displays amount of money in account
*/
public static void displayBalance(double accBalance){
System.out.printf("\nYour current balancre is $%.2f\n", accBalance);
}
/**
*
* #param accBalance given account balance for account
* #param withdraw amount to be taken out of account
* #return if withdraw !> accBalance, then it will be subtracted from it and resultant amount will be displayed
*/
public static double withdraw(double accBalance, double withdraw){
System.out.println("How much would you like to withdraw?");
withdraw = kbd.nextDouble();
if (accBalance < withdraw){
System.out.printf("Cannot withdraw more than balance" + "\nYour current balance is: " + accBalance + "\n");
return accBalance;
}
else {
double newBalance = accBalance - withdraw;
System.out.println("Your new balance is: " + newBalance);
return newBalance;
}
}
}
Well first of all your while loop will only execute if the result of the ID check is "error". You need to change the condition of the loop to 'true' so it will run regardless, as this is the main event loop:
do {
if (res.equals("error")){
attemptNumber++;
System.out.println("Invalid password, please try again.");
if (attemptNumber == MAXATTEMPTS){
System.out.print("Maximum Login Attempts Reached.");
System.exit(0);
}
}
else {
double balance = Double.parseDouble(res);
while(true){
int option = menu();
switch (option) {
case 1:
displayBalance(balance);
break;
case 2:
deposit(balance, balance);
break;
case 3:
withdraw(balance, balance);
break;
case 4:
System.out.println("Thank you for banking with us, have a nice day!");
System.exit(0);
}
}
}
}
while (true);

bank program not working as expected

I know that it is not a debugger site but I just wanted to ask what I am doing wrong in this piece of code.
When I run the program I first add a new account, then when I deposit or withdraw it says Wrong Password. Here is my code
Code :
import java.io.*;
import java.util.Random;
public class BankA {
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);
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[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];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a) {
if( pass == p) {
accounts[i].withdraw(Money);
System.out.println(" Amount withdrawn successfully");
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println(" Account number not found.");
}
public void Deposit(int Account_Number, int pass, double Money) {
for (int i =0; i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a) {
if( pass == p) {
accounts[i].withdraw(Money);
System.out.println(" Amount deposited successfully");
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println(" Account number not found.");
}
public void Transactions(int Account_Number, int pass) {
for(int i = 0;i<numOfAccounts; i++) {
int a = accounts[i].getAccountNum()[0];
int p = accounts[i].getAccountNum()[1];
if (Account_Number == a ) {
if( pass == p) {
System.out.println(accounts[i].getAccountInfo());
System.out.println(" Last transaction: " + accounts[i].getTransactionInfo(accounts[i].getNumberOfTransactions()-1));
return;
} else {
System.out.println("Wrong Password");
}
}
}
System.out.println("Account number not found.");
}
}
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++;
}
}
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++;
}
}
}
}
}
You have a problem in your code where you create the new account:
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
You're calling myBank.AddNewAccount() twice on that line, which means that the account number printed will be for account #1, while the password printed will be for account #2.
Change it so that you're only creating one account and printing the details for it:
int[] newAccount = myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + newAccount[0]+"\nYour password : "+ newAccount[1]);
Also, while I tested your code, it seems you're calling withdraw() instead of deposit() in Bank.deposit():
accounts[i].withdraw(Money);
It's because myBank.AddNewAccount(Name, Balance) is getting called twice in below statement, actually it should be called only once per account.
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
make below changes to your code and sit should work fine:
int[] arrDetails= myBank.AddNewAccount(Name, Balance);//added new line of code
System.out.println("Account Has been created\n Account number: " + arrDetails[0]+"\nYour password : "+ arrDetails[1]);// modified existing code
Final code for Case 1 should be:
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;
Your problem is here:
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
Why do you add a new account twice in the above method? This creates a duplicate account with a different password. Change the above line to this.
myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + myBank.getAccountNum()[0].+"\nYour password : "+ myBank.getAccountNum()[1]);
Your creating two objects and returning second obj password.
System.out.println("Account Has been created\n Account number: " + myBank.AddNewAccount(Name, Balance)[0]+"\nYour password : "+ myBank.AddNewAccount(Name, Balance)[1]);
In Above code your calling myBank.AddNewAccount two times so, it is creating two objects and THE PASSWORD YOUR PRINTING IS SECOND OBJECT PASSWORD, that's why it is showing wrong password.
you can use this code.
int[] details = myBank.AddNewAccount(Name, Balance);
System.out.println("Account Has been created\n Account number: " + details [0]+"\nYour password : "+ details[1]);

My Code won't stop printing in a loop

import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank
{
double balance = 0;
double amount = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
//Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while
(!quit);
}
}
My code otherwise works fine but I can't seem to figure out why it won't stop repeatedly printing my error message for the user. If someone can point out my error for me that would be fantastic. I did have this same code in another question however they fixed my problem that I had in the last question and were unable to answer the problem that arose here.
You need to remove or comment out the following line from your code :
in.useDelimiter("\n");
This is causing the the character "\n" to be passed to the amount = in.nextDouble(), which in turn causes the InputMismatchException to be thrown , thus resulting in an infinite loop.
UPDATE : Working code and the Sample output for your convinience:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank {
public static void main(String[] args) {
double balance = 0;
double amount = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
System.out.print("User Input :");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println("Available Balance is : " + account1.getBalance());
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while (!quit);
}
}
}
Sample Output :
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :1
How Much would you like to deposit?
100
Depositing: 100.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :25
Error: Choice not recognized please choose again.
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :2
How Much would you like to withdraw?
25
Withdrawing: 25.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :3
Checking Balance.
Available Balance is : 75.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :0
Thanks for Using BankAccount Banking System!
Try this
String value = in.nextLine();
String v="";
for(int i=0;i<value.length();i++)
if(value.charAt(i)!='\n')
v+=value.charAt(i);
double amount =-1;
if(v!=null)
amount = Double.parseDouble(v);

Bank Account Java Program

I am creating a bank account program for my java class that is suppose to manage up to 5 different bank accounts. The program has to allow the creation of a new account, which I have done, allow deposit and withdraw, which is also done, the 2 parts I cannot get to work are 1: the bank can only have up to 5 accounts, so if a 6th is trying to be created, a message comes up saying that 5 are already created, and 2: one of the options has to print out all the account balances of current accounts in the bank.
This is my code as of now:
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
The program runs fine, I just need to add these two options, and cannot get them to work properly, how would I go about doing this? Also, options 3 and 4 should not work if no accounts have been created yet. Thanks in advance.
UPDATE: this is what I tried, I keep getting a this method must return type int error.
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();
}
}
UPDATE 2: I added a return statement, now when it runs it will open accounts up to number 5, but for every account after number 5 it just says the account number is 5 again instead of not opening an account.
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;
}
Its pretty simple. Create a list of size 5 and add the account into that list when user is created one. Before adding just make a check whether list size <= 5. If it is true, go ahead and add the account, otherwise throw an error
For option 2, just iterate through the list and display the results
1; in the openNewBank account method; before creating the new Bank account and increasing the count by 1; check if the number of account is already at 5 or higher and if it is dont create the account and dont increase the count.
2: Loop through the number of account variable and print.
I added password system to it. and nice looking account 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");
}
}
}
}
}

Control Statements: Why is my 'New Balance' change when I 'charge to credit' then 'pay credit' twice?

I tried reading from the start of this Java book and do some of its exercises for summer vacation. The I came up with this problem:
"(Credit Limit Calculator) Develop a Java application that determines whether any of several
department-store customers has exceeded the credit limit on a charge account.....For those customers whose credit limit is exceeded, the program should display
the message "Credit limit exceeded"."
My code works only if I use Charge to Credit ONCE. If I use Charge to Credit again, my new balance value will change. Example:
* Acc # = 123
* Beginning Balance = 20000
* Credit Limit = 25000
* Select Transaction = 1 (Charge to Credit)
* Amount to charge = 4000
* Select Transaction = 2 (Pay credit)
* Amount to pay = 2000 [My balance should now be 22000)
* Select Transaction = 1 (Charge to Credit)
* Amount to charge = 10000 [This shud exceed credit limit]
* Select Transaction = 3 (Balance Inquiry)
* My new balance is now 18000
This is my problem now. My new balance should still be 22000 since the credit limit has exceeded. But now its 18000. I don't know where it went wrong so I need help, please.
So here's my code:
Customer.java
import java.util.Scanner;
public class Customer {
Scanner input = new Scanner (System.in);
int accNum,
beginBal,
creditLimit;
int itemsCharged,
creditsPaid,
newBalance;
int transaction;
String action;
public void start (){
System.out.print("\nAccount Number: ");
accNum = input.nextInt();
System.out.print("Beginning Balance: ");
beginBal = input.nextInt();
System.out.print("Credit Limit: ");
creditLimit = input.nextInt();
transaction();
}
public void transaction (){
boolean loop = true;
while (loop){
System.out.println("\n[1] Charge to Credit \n[2] Pay Credit \n[3] Balance Inquiry/Exit");
System.out.print("Select Transaction #: ");
transaction = input.nextInt();
switch (transaction){
case 1:
System.out.print("\n--CHARGE TO CREDIT-- \nEnter amount: ");
itemsCharged = input.nextInt();
newBalance = beginBal + itemsCharged - creditsPaid;
if (newBalance > creditLimit){
System.err.println("Credit Limit Exceeded!");
newBalance -= itemsCharged;
} else {
System.out.println("Amount charged.");
}
break;
case 2:
System.out.print("\n--PAY CREDIT-- \nEnter amount: ");
creditsPaid = input.nextInt();
newBalance = beginBal + itemsCharged - creditsPaid;
if (creditsPaid > newBalance){
System.err.println("Invalid Amount!");
newBalance -= creditsPaid;
} else {
System.out.println("Payment posted!");
newBalance = beginBal + itemsCharged - creditsPaid;
}
break;
case 3:
System.out.println("\n--BALANCE INQUIRY-- \nNew Balance: " + newBalance);
restart();
break;
default:
System.err.println("Invalid number!");
transaction();
break;
}
}
}
public void restart (){
System.out.println("\nDo you have another transaction? [Y/N]");
System.out.print("Select Action: ");
boolean loop = true;
while (loop){
action = input.nextLine();
switch (action){
case "Y":
start();
break;
case "N":
System.err.println("Terminated.");
System.exit(0);
break;
}
}
}
} // end class
CreditLimitCal.java
public class CreditLimitCal {
public static void main (String[] args){
Customer cus = new Customer();
cus.start();
}
}
this line:
newBalance = beginBal + itemsCharged - creditsPaid;
Doesn't need to subtract creditsPayed, you've already done that previously when the user paid off part of the balance.
newBalance should only be modified by one thing each time, so for case 1:
newBalance = newBalance + itemsCharged;
case 2:
newBalance = newBalance - creditsPaid;

Categories

Resources