I am still having trouble figuring out how the heck the most efficient way to do this is.. Basically, I am trying to make the balance = 0 for every object in the Account array created. I tried using a for loop and set balance = 0for each account created, but I am unsure of how to make this work since the balance variable is created in the class that has all of the methods. I have been trying to this problem all day, but no luck. Thanks.
Main method:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
for (int count2; count2 < 30; count2++)
{
balance = 0; //Initial balance is always set to zero to be able to run fresh program every time
}
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Supporting class:
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private int acctNumber;
private String name;
private balance;
//Defines owner, account number, and initial balance.
public Account(String owner, int account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
From an outside class, you can only interact with Account in the way exposed in its visible (e.g. public) API.
In this case, the current way to do this would be to withdraw() the current balance:
acct[i].withdraw(acct[i].getBalance());
Though this specific case would put the balance into the negatives because you charge a fee for a withdrawal (which is hidden from the calling class).
If you were to expose a setBalance method on Account, you could instead do
acct[i].setBalance(0);
However on closer look, it seems like what you are having trouble with is actually initializing the array of accounts. You can do this like this:
for (int count2; count2 < 30; count2++)
{
acct[count2] = new Account(owner, count2, 0);
}
Related
I am working on a java program that basically simulates a bank account to make deposits, withdraws, display balance, etc. I have done almost everything. I am just stuck in one part to be finished. The program asks the user what is the starting balance and interest rate. The only thing I am missing is that I need to display a message that the account is inactive when the balance goes under $25, that is done. Now I need a message saying that the account is ACTIVE but only once the balance went down under 25 and then came back over 25. Every way that I have tried it shows the active every time the balance is more than 25, I just need it to display once after coming back from being inactive but can't manage a way how to do it. Any ideas would be appreciated, here is my code:
///BankDemo class
import java.util.Scanner;
public class BankDemo {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float startingBalance;
float interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextFloat();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextFloat();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
while(startingBalance > -1) {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else {
System.out.print("Error, option not valid\n");
}
}
}
}
///BankAccount class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
float charge = 1;
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance += valueD;
numDeposits++;
}
public void withdraw() {
float valueW;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextFloat();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 25) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
float monRate = annualRate / 12;
float monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
///SavingsAccount class
public class SavingsAccount extends BankAccount {
private boolean active;
public SavingsAccount(float bal, float rate) {
super(bal, rate);
if(bal < 25)
active = false;
else
active = true;
}
public void withdraw() {
if(active)
super.withdraw();
}
public void deposit(float amount) {
if(!active) {
if(amount + balance < 25)
return;
}
super.deposit();
}
public void withdrawals() {
if(numWithdrawals > 4) {
monthlyServCharg += numWithdrawals - 4;
}
if(balance < 25)
active = false;
}
}
You show the messages only if the active status changes, i.e. when you deactivate the account:
if(balance < 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
And when you activate it again:
if( balance >= 25 && !active) {
//print message here
active = true;
}
To achieve that in BankAccount it already needs the active flag that SavingsAccount has (the subclass wouldn't need it then). You probably also want to disallow withdrawals if the account isn't active.
My question is in relation to my line of code resembling an ATM. The current balance being 10000, What i have written shows a message to the user that if they withdraw over the given balance that it is Insufficient balance. However the balance continues to change thus when Inquiring balance the balance is now < the allowed balance. My question is how should i go about resetting the double value for the balance when the Insufficient balance message is shown to the user?
Here is my code.
import java.util.Scanner;
class app {
public static void main(String[] args)
{
long pin = 2927942074l;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
while (attempts > 0) {
Scanner keyboardpin = new Scanner(System.in);
long input = keyboardpin.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
while (true) { // Keep printing your options unless "Quit" is chosen
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
Scanner menuselect = new Scanner(System.in);
int menuinput = menuselect.nextInt();
if (menuinput == a) {
System.out.println(balance);
continue;
}
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
balance = (balance - withdrawbalace);
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
System.out.println("Youre new balance is " + balance);
}
if (menuinput == c) {
}
if (menuinput == d) {
break;
}
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
}
}
} else {
System.out.println("Wrong");
attempts--;
System.out.println("You have " + attempts + " attempts remaining.");
}
}
}
}
Just check whether the user has enough balance before subtracting the amount.
if (menuinput == b) {
System.out.println("Please enter a withdrawal amount.");
Scanner withdrawamount = new Scanner(System.in);
double withdrawbalace = withdrawamount.nextDouble();
if (withdrawbalace > balance)
System.out.println("Insufficient balance");
if (withdrawbalace <= balance)
balance = (balance - withdrawbalace);
System.out.println("Youre new balance is " + balance);
}
Your main problem has been solved in the previous answer, but your code logic has some errors. I have fixed it for you.
import java.util.Scanner;
class app {
public static void main(String[] args) {
final long pin = 2927942074L;
double balance = 10000.0;
int attempts = 3;
System.out.println("Please enter your pin.");
Scanner keyboard = new Scanner(System.in);
while (attempts > 0) {
long input = keyboard.nextLong();
if (input == pin) {
System.out.println("Correct");
System.out.println("Welcome to your ATM");
// Keep printing your options unless "Quit" is chosen
while (true) {
int a = 1;
int b = 2;
int c = 3;
int d = 0;
System.out.println(a + " - Inquire Balance");
System.out.println(b + " - Withdraw");
System.out.println(c + " - Deposit");
System.out.println(d + " - Quit");
System.out.println("Please select what you want to do.");
int menuInput = keyboard.nextInt();
if (menuInput == a) {
System.out.println(balance);
} else if (menuInput == b) {
System.out.println("Please enter a withdrawal amount.");
double withdrawBalance = keyboard.nextDouble();
if (balance >= withdrawBalance) {
balance -= withdrawBalance;
System.out.println("Your new balance is " + balance);
} else System.out.println("Insufficient balance");
} else if (menuInput == c) {
// Deposit code here
} else if (menuInput == d) break;
}
} else {
attempts--;
if (attempts == 0) {
System.out.println("Maximum number of attempts exceeded");
break;
}
System.out.println("Wrong");
System.out.println("You have " + attempts + " attempts remaining.");
}
}
keyboard.close();
}
}
And here are some tips...
Try to choose meaningful variable names.
If the variable has a constant value make it final
If the variable name consists of two, or more, words capitalize the first letter of the second word (eg. menuInput)
If you check the same condition for different cases you can use switch or if, else if, else
Never forget to close the objects you used to release memory
Good Luck
I cannot figure out how to get the double balance1 in my main method to equal the double acctBal in my menu method. I assigned 0 to acctBal because i am not sure how to have it equivalent to whatever balance1 is. I put some asterisks next to the lines i am talking about.
public class ATM {
public static Scanner kbd;
public static void main(String[] args) {
String acctNum, acctPword;
String balance;
int x = 1;
kbd = new Scanner(System.in);
System.out.print("Enter your account number: ");
acctNum = kbd.nextLine();
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
balance = checkID(acctNum, acctPword);
double balance1 = Double.parseDouble(balance);
System.out.println("You currently have $" + String.format("%.2f",balance1));*********************************
while (balance.equals("error") && x <4){
System.out.println("Wrong password try again.");
System.out.print("Enter your account password: ");
acctPword = kbd.nextLine();
x++;
}
if (x == 4)
System.out.println("Maximum number of attempts reached, Please try again later.");
if (x == 1){
menu();
}
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 checked
* #param pwd The password to be checked
* #return If the account information is valid, returns the current 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";
if (acctNum.equals("44567-5") && pwd.equals("mypassword")){
result = "520.36";
return result;
}
if (acctNum.equals("1234567-6") && pwd.equals("anotherpassword")){
result = "48.20";
return result;
}
if (acctNum.equals("4321-0") && pwd.equals("betterpassword")){
result = "96.74";
return result;
}
return result;
}
public static void menu(){
int x = 0;
double acctBal = 0.0, deposit = 0.0, withAmnt = 0.0;**********this acctBal needs to equal balance1.
System.out.println("1. Display Balance \n2. Deposit\n3. Withdraw\n4. Log Out");
x = kbd.nextInt();
switch(x){
case 1:
displayBalance(acctBal);
break;
case 2:
deposit(acctBal, deposit);
break;
case 3:
withdraw(acctBal, withAmnt);
break;
case 4:
System.out.println("Have a nice day.");
break;
}
}
public static double deposit(double acctBal, double depAmnt){
System.out.print("How much money would you like to deposit? $");
depAmnt = kbd.nextDouble();
acctBal = acctBal + depAmnt;
System.out.println("Your balance is now at $" + String.format("%.2f", acctBal));
return acctBal;
}
public static double withdraw(double acctBal, double withAmnt){
System.out.print("How much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
if (acctBal <= 0){
System.out.println("You do not have any money.");
return acctBal;
}
if (acctBal < withAmnt){
System.out.print("You do not have enough money.\nHow much money would you like to withdraw? $");
withAmnt = kbd.nextDouble();
}
else{
acctBal = acctBal - withAmnt;
}
return acctBal;
}
public static double displayBalance(double balance){
System.out.println("Your balance is $" + String.format("%.2f", balance));
return balance;
}
You can change the menu() method to accept a parameter (called balance) and pass the value from main while calling menu() method, e.g.:
public static void menu(double acctBal){
double deposit = 0.0; //Other variables
}
And call it from main with balance, e.g.:
if (x == 1){
menu(balance);
}
Your code has a problem, you do not treat the situation where checkID returns "error". You cannot assign "error" to some String and then try to convert a double from that String.
Minor fix
balance = checkID(acctNum, acctPword);
double balance1 = 0.0;
if (balance.equals("error"))
{
// TODO: do something with invalid number.
}
else
{
balance1 = Double.parseDouble(balance);
}
System.out.println("You currently have $" + String.format("%.2f",balance1));
I am getting an error on this program for some reason and I have no idea what it means. I tried googling around, but nothing related to my issue is coming up. Does this have to do with an IOException by any chance? Also, where does the input get stored? In the class file? For example: if I was to input money into the account, would the inputed value be saved in a different file, or does the fact that I made an array of 30 account for a double amount of all 30 objects created?
Main class:
import java.util.Scanner;
import java.text.NumberFormat;
public class Account2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Account[] acct = new Account[30];
System.out.println("Enter your account number (1-30): ");
int key = scan.nextInt() - 1;
int reset = 0;
while (reset == 0)
{
System.out.println("Enter W for withdrawl; D for deposit; X to escape");
char choice = scan.next().charAt(0);
if (choice == 'W' || choice == 'w' || choice == 'D' || choice == 'd' || choice == 'x' || choice == 'X')
{
if (choice == 'W' || choice == 'w')
{
System.out.println("Enter amount to withdraw: ");
Double withdraw1 = scan.nextDouble();
if (withdraw1 <= acct[key].getBalance())
{
acct[key].withdraw(withdraw1);
System.out.println("User # " + key++ + " funds after withdraw: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Insufficient funds.");
}
if (choice == 'D' || choice == 'd')
{
System.out.println("Enter amount to deposit: ");
Double deposit1 = scan.nextDouble();
if (deposit1 > 0)
{
acct[key].deposit(deposit1);
System.out.println("User # " + key++ + " funds after deposit: " + acct[key].getBalance() + "$");
System.out.println("User # " + key++ + " funds after interest: " + acct[key].addInterest() + "$");
reset++;
}
else
System.out.println("Use the withdrawl feature to withdrawl money.");
}
if (choice == 'x' || choice == 'X')
System.out.println("Thank You for using this bank.");
reset++;
}
else
{
System.out.println("Invalid entry, please try again");
reset = 0;
}
}
}
}
Second Class:
import java.text.NumberFormat; //links to Part2
public class Account
{
private final double RATE = 0.03; //Interest is 3%
private long acctNumber;
private double balance;
private String name;
//Defines owner, account number, and initial balance.
public Account(String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//deposits a specified amount and returns new balance
public double deposit(double amount)
{
balance = balance + amount;
return balance;
}
//withdraws the specified amount from the account and applies the fee
// + returns balance
public double withdraw(double amount)
{
int fee = 1;
balance = balance - amount - fee;
return balance;
}
//Adds interest to the account
public double addInterest()
{
balance += (balance * RATE);
return balance;
}
public double getBalance()
{
return balance;
}
//returns a one line description of the account as a string
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "/t" + name + "/t" + fmt.format(balance);
}
}
Error message:
Enter your account number (1-30):
5
Enter W for withdrawl; D for deposit; X to escape
d
Enter amount to deposit:
50
Exception in thread "main" java.lang.NullPointerException
at Account2.main(Account2.java:40)
You're trying to acces an index of acct but the array is empty Account[] acct = new Account[30];
You should first fill the array, try to make the user create an account first.
The else if section of deposit is not working and same is the case with else if section of no for updating the balance.
public class BankAccount
{
static double Balance;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the account holder's name...");
String Name = sc.next();
System.out.println("enter his account number...");
long AccNo = sc.nextLong();
System.out.println("enter his type of account...");
String AccTyp = sc.next();
System.out.println("enter his current balance...");
Balance = sc.nextDouble();
System.out.println("Do you want to update your balance, press y for yes and n for no...");
if(sc.next().equalsIgnoreCase("y") == true)
{
System.out.println("To withdraw money press w, To deposite the same, press d");
if(sc.next().equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(sc.next().equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else
System.out.println("Thank you for your transaction");
}
else if(sc.next().equalsIgnoreCase("n") == true)
{
System.out.println("Thank you for your transaction");
}
System.out.println("Thank you for your transaction");
}
public static double Withdraw(double a)
{
Balance = Balance - a;
return Balance;
}
public static double Deposit(double b)
{
Balance = Balance + b;
return Balance;
}
}
Don't keep invoking the next() method:
if(sc.next().equalsIgnoreCase("w") == true)
...
else if(sc.next().equalsIgnoreCase("d") == true)
Instead the code should be something like:
String response = sc.next();
if(response.equalsIgnoreCase("w"))
...
else if(response.equalsIgnoreCase("d"))
...
If 'if' block execute sc.next() then 'else' block can't execute sc.next(). Assign the input to a variable action like this.
String action=sc.next();
if(action.equalsIgnoreCase("w") == true)
{
System.out.println("Enter the amount the account holder withdrawed");
double withdraw = sc.nextDouble();
double Bal = Withdraw(withdraw);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}
else if(action.equalsIgnoreCase("d") == true)
{
System.out.println("Enter the amount the account holder deposited");
double deposit = sc.nextDouble();
double Bal = Deposit(deposit);
System.out.println("Account holder " +Name+ " with account number " +AccNo+ " and account type " +AccTyp+ " has the new balance = "+Bal);
}