ATM method program (possible logic or bracket errors) - java

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

Related

How do I loop for only specific "case" in switch/case?

I used switch/case to print yearly earnings depending on the bank account the user choose and I want to make this program, whenever the user enters inappropriate input, print "inappropriate input" message and let the user to re-enter the bank account they want to choose. But, currently my code only prints "inappropriate input" message. How can I fix it?
public static void main(String[] args) throws Exception
{
//initialize variables
String bank = "";
double money;
//asks the user to type the amount of money
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
//if the input is inappropriate, ensures the user to type the correct input
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.nextLine();
}
}
//asks user to type the type of account they want
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
//print yearly earnings depending on the type of account that user chose
switch (bank) {
case "A" , "C": //if the user enters A or C, 1.5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
break;
case "B": //if the user enters A or C, 2% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.02 * money)*100)) / 100.0);
break;
case "X": //if the user enters A or C, 5% of money will be yearly earnings
System.out.println("You can make $" + (Math.round((0.05 * money)*100)) / 100.0);
break;
default:
System.out.println ("This is inappropriate input. Please enter the type of account you want");
bank = myinput.nextLine();
}
//closing scanner
myinput.close();
}//end main
You can have one boolean variable for getting out of while-loop.
Flag is set to false in switch/case because while(false) wont iterate further.
boolean flag = true;
while(flag){
switch(bank){
case "A","C":
System.out.println("You can make $" + (Math.round((0.015 * money)*100)) / 100.0);
flag = false; //put this in all case.
break;
...
}
}
package com.javatutorial;
import java.util.Scanner;
class Main{
public static void main(String[] args) throws Exception
{
String bank = "";
double money = 0;
boolean valid = false;
Scanner myinput = new Scanner (System.in);
System.out.print("Please enter the amount of money you want in the bank: ");
while (true) {
try {
money = myinput.nextDouble();
break;
} catch (Exception e) {
System.out.println("This is inappropriate. Please enter the amount of money you want in the bank: ");
myinput.next();
}
}
do {
System.out.println("Please enter the type of account you want: ");
bank = myinput.next();
switch (bank) {
case "A":
case "C":
System.out.println("You can make $" + (Math.round((0.015 * money) * 100)) / 100.0);
valid = true;
break;
case "B":
System.out.println("You can make $" + (Math.round((0.02 * money) * 100)) / 100.0);
valid = true;
break;
case "X":
System.out.println("You can make $" + (Math.round((0.05 * money) * 100)) / 100.0);
valid = true;
break;
default:
System.out.println("This is inappropriate input. Please enter the type of account you want");
}
}while( !valid);
}
}

java - withdraw from bank account using a method

Building a basic bank account with Java using methods. I am creating a new method to withdraw from the bank account. This is the code that I came up with right now, but on netbeans it shows that there are errors.
I created a new method called withDrawal. This code below is for the withdrawing from account and to not let the balance in the account go below zero!
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
Java file
package grossmontbank;
import java.util.Scanner;
public class GrossmontBank
{
//class variables (global - accessible throughout this class)
//scanner object to be used throughout
private static Scanner input = new Scanner(System.in);
//array of blank accounts
private static final int MAX_ACCOUNTS = 50;
private static Account[] accounts = new Account[MAX_ACCOUNTS];
//total accounts created
private static int totalAccounts = 0;
//main class mimics a bank teller
public static void main(String[] args)
{
char choice;
//loop until 'Q' is entered
do
{
choice = getChoice(); //getChoice() will only return with a C, B, W, D or Q
if(choice != 'Q')
{
switch(choice)
{
case 'C': createAccount();
break;
case 'B': checkBalance();
break;
case 'W':
break;
case 'D':
break;
}
}
}while(choice != 'Q');
closeBank(); //outputs all account holders and 'closes' the bank
}
/*method checkBalance calls method findAccount()
* if account exists, calls Account method checkBalance()
*/
private static void checkBalance()
{
int accountIndex = findAccount();
//findAccount() returns index of account if found, -1 if not found
if(accountIndex != -1)
{
accounts[accountIndex].checkBalance();
}
else
{
System.out.println("Account does not exist");
}
}
/*method checkIfExists determines if account holder already exists
* returns true if account holder exists, false otherwise
*/
private static boolean checkIfExists(String firstName, String lastName)
{
//loops through account array to see if account name already exists
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(firstName)
&& accounts[i].getLastName().equalsIgnoreCase(lastName))
{
System.out.println("Account holder already exists. Please verify and re-enter. ");
return true;
}
}
return false;
}
/*method closeBank prints out closing statement
* prints out list of all account holders
*/
private static void closeBank()
{
System.out.println("Closing the follow accounts:");
for(int i = 0; i < totalAccounts;i++)
{
//printing an account object invokes the Account class method toString()
//prints first and last name only
System.out.printf(" %s%n",accounts[i]);
}
System.out.println("Grossmont Bank is officially closed.");
}
/*method createAccount creates a single bank account
* checks to ensure account holder does not already exist
* returns Account object
*/
private static void createAccount()
{
String first, last, initial;
boolean exists = false;
//only create a new account if MAX_ACCOUNTS has not been reached
if(totalAccounts < MAX_ACCOUNTS )
{
//loop until a new account name has been entered
do
{
System.out.print("Enter your first name: ");
first = input.next();
System.out.print("Enter your last name: ");
last = input.next();
exists = checkIfExists(first,last);
}while(exists == true);
System.out.print("Will you be making an initial deposit? Enter Yes or No: ");
initial = input.next();
//if no initial deposit, call 2 parameter constructor, otherwise call 3 param one
if(initial.equals("No"))
{
accounts[totalAccounts] = new Account(first,last);
}
else
{
System.out.print("Enter initial deposit amount: ");
accounts[totalAccounts] = new Account(first,last, input.nextDouble());
}
//increment totalAccounts created (used throughout program)
totalAccounts++;
}
else
{
System.out.println("Maximum number of accounts has been reached. ");
}
}
/*method findAccount asks for first and last name
* searchs for account holder in array
* if exists, returns array index of this account
* if doesn't exist, returns '-1'
* called from checkBalance()
*/
private static int findAccount()
{
String first, last;
System.out.print("Enter first name: ");
first = input.next();
System.out.print("Enter last name: ");
last = input.next();
//loops through account array
for(int i = 0; i < totalAccounts;i++)
{
//compares the names, ignoring upper/lower
if(accounts[i].getFirstName().equalsIgnoreCase(first)
&& accounts[i].getLastName().equalsIgnoreCase(last))
{
return i; //returns the index of the account
}
}
return -1; //if account not found
}
/* method getChoice() outputs options
* inputs choice from user and validates
* returns choice char
*/
private static char getChoice()
{
char choice;
//output menu options
System.out.println();
System.out.println("Welcome to Grossmont Bank. Choose from the following options: ");
System.out.println(" C - create new account");
System.out.println(" B - check your balance");
System.out.println(" D - deposit");
System.out.println(" W - withdrawal");
System.out.println(" Q - quit");
//loop until a valid input is entered
do
{
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'C' || choice == 'B' || choice == 'D' || choice == 'W' || choice == 'Q')
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
}while(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
private static void withDrawal()
{
int accountIndex = findAccount();
int verifyPin = checkPin (!=0);
if(accountIndex != -1)
if(verifyPin !=-2)
{
accounts[accountIndex].withDrawal();
accounts[verifyPin].checkPin();
int withDra = input.nextInt();
}
else
{
System.out.println("Account does not exist!");
System.out.printf("Enter amount you want to withdraw: ");
}
}
}

How to add an integer in a string, java and limit user input

Hi I needed help with doing a calculation in this right here. On the line where it has single, i want to add the number to the calculation but it just adds it as if im just writing the number itself in a sentence. How do i add it as if its a calculation, im very stuck and need help. (Its the last line of code). I also wanted to know how i can limit the amount of letters a user can input, since i only want them to either enter 's' or 'm'. How can i limit them to only these two so they dont use a letter like 'g' for example, since that wont work.
import java.util.Scanner;
public class FedTaxRate
{
public static void main(String[] args)
{
String maritalStatus;
double income;
int single = 32000;
int married = 64000;
Scanner status = new Scanner(System.in);
System.out.println ("Please enter your marital status: ");
maritalStatus = status.next();
Scanner amount = new Scanner(System.in);
System.out.print ("Please enter your income: ");
income = amount.nextDouble();
if (maritalStatus.equals("s") && income <= 32000 )
{
System.out.println ("The tax is " + income * 0.10 + ".");
}
else if (maritalStatus.equals("s") && income > 32000)
{
System.out.println ("The tax is " + (income - 32000) * 0.25 + single + ".");
}
}
}
To answer your second question about limiting the input, you can try using a switch case statement. The default allows you to write code for the case when maritalStatus is not equal to either "s" or "m". You can also create a do-while loop to keep asking for input until maritalStatus is equal to either "s" or "m".
Scanner status = new Scanner(System.in);
String maritalStatus = status.nextLine();
do {
System.out.println("Enter your marital status.")
switch (maritalStatus) {
case "s":
// your code here
break;
case "m":
// your code here
break;
default:
// here you specify what happens when maritalStatus is not "s" or "m"
System.out.println("Try again.");
break;
}
// loop while maritalStatus is not equal to "s" or "m"
} while (!("s".equalsIgnoreCase(maritalStatus)) &&
!("m".equalsIgnoreCase(maritalStatus)));
You only need one Scanner. You can use an else with your income test. I would suggest you calculate the tax once, and then display it with formatted IO. Something like,
public static void main(String[] args) {
int single = 32000;
int married = 64000;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your marital status: ");
String maritalStatus = sc.next();
System.out.print("Please enter your income: ");
double income = sc.nextDouble();
double tax;
if ("s".equalsIgnoreCase(maritalStatus)) {
if (income <= single) {
tax = income * 0.10;
} else {
tax = (income - single) * 0.25 + single;
}
} else {
if (income <= married) {
tax = income * 0.10;
} else {
tax = (income - married) * 0.25 + married;
}
}
System.out.printf("The tax is %.2f.%n", tax);
}

Arrays and bank accounts in 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!

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