Every time I loop my interestRate variable is not resetting. I want it to update my interest when looping, at first I have the correct value of 1650 but when it comes to the third input all the interest from first, second, and third will just sum up. I'm expecting 1760.0 as the output but it shows 1925.0.
import java.util.*;
class SavingsAccount {
private double balance;
public static double interestRate = 0;
static double updatedrate;
public static void setInterestRate(double newRate){
interestRate = newRate;
}
public static double getInterestRate(){
return interestRate;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance=balance + amount;
}
public double withdraw(double amount){
if(balance>=amount){
balance= balance-amount;
}
else{
amount=0;
}return amount;
}
public void addInterest(){
double interest = balance * getInterestRate();
balance = balance + interest;
}
public static void showBalance(SavingsAccount account){
System.out.println("Your new Balance is "+ account.getBalance());
}
public class RunSavingsAccount {
public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount();
Scanner sc = new Scanner(System.in);
try{
System.out.print("Enter Interest Rate: " );
double rate1 = sc.nextDouble();
savings.setInterestRate(rate1);
System.out.print("Enter Deposit Amount: " );
double balance1 = sc.nextDouble();
savings.deposit(balance1);
System.out.println("Your balance is: "+ balance1);
boolean bol = false;
while(!bol){
System.out.print("Press D for another deposit or W to withdraw or E to exit: ");
String transaction = sc.next();
if (transaction.equals("d")) {
System.out.print("Enter Deposit Amount: " );
double balance2 = sc.nextDouble();
savings.deposit(balance2);
savings.addInterest();
savings.showBalance(savings);
}
else if(transaction.equals("w")){
System.out.print("Enter Withdraw Amount: " );
double with = sc.nextDouble();
savings.withdraw(with);
System.out.println("");
System.out.println("Your have succesfully withdraw: "+ with);
savings.showBalance(savings);
}
else if(transaction.equals("e")){
System.out.println("Thank You Please Come Again.");
bol = !bol;
}
else{
System.out.println("Invalid Input");
}
}
}
catch(Exception e){
System.out.print("Invalid Input");
}
}
}
Output:
Enter Interest Rate: .10
Enter Deposit Amount: 500
Your balance is: 500.0
Press D for another deposit or W to withdraw or E to exit: d
Enter Deposit Amount: 1000
Your new Balance is 1650.0
Press D for another deposit or W to withdraw or E to exit: d
Enter Deposit Amount: 100
Your new Balance is 1925.0
Press D for another deposit or W to withdraw or E to exit:
You're adding interest on the whole balance after every deposit:
savings.deposit(balance2);
savings.addInterest();
Technically that would be correct if you do a deposit every year.
I'm not sure what you're trying to simulate here. Maybe you should have a separate command for adding interest only once at the end of the year or so.
if (transaction.equals("i")) {
savings.addInterest();
savings.showBalance(savings);
}
else if (transaction.equals("d")) {
System.out.print("Enter Deposit Amount: " );
double balance2 = sc.nextDouble();
savings.deposit(balance2);
savings.showBalance(savings);
}
The application does exactly what it is supposed to do.
public void deposit(double amount){
balance=balance + amount;
}
public void addInterest(){
double interest = balance * getInterestRate();
balance = balance + interest;
}
You always first add the deposit and then addInterest,so
balance: 500
addDeposit(1000) => balance 1500
addInterest => balance = 1500 + (1500 * 0,1) = 1650
addDeposit(100) => balance = 1650 + 100 = 1750
addInterest() => balance = 1750 + (1750 * 0,1) = 1750 + 175 = 1925
I guess you do not meant to have the interest on the full balance sum, or you made some other assumption which is different.
Generally, I would recommend you to get an IDE with a debugger that allows step-by-step execution of the code so you can get more insight on what is happening.
Related
I am working on a school project and I am pretty much done but have been stuck in a detail. I am asking the user to enter their starting balance and the interest rate, to make it easier for the user just asking to enter a whole number like 1, 2, 3, etc. Example, if they enter 1000 in starting balance and 9% in the interest rate the result would 1750.00, the expected result is 1007.50 which comes when the user enters .09%, is there a way to change any number the user enters to that so when they enter 9 it transforms it into .09. If you run the code, enter starting balance and rate and then select "M", you will see those numbers. Any ideas will be appreciated, here is the 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();
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();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
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 if("e".equals(userInput)) {
ba.exit();
} else {
System.out.print("Error, option to valid");
}
}
}
///BankAccount Class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
public BankAccount() {
balance = 0;
numDeposits = 0;
numWithdrawals = 0;
annualRate = 0;
monthlyServCharg = 0;
}
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
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 < 1) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numDeposits++;
}
public void totalBalance() {
System.out.print("Balance is: " + 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", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
In your overload constructor, set annualRate equal to (interestRate / 100) to convert it to a percentage. Also, as a side node, you don't need to initialize all the variables on the default constructor because they're initialize to 0 since they're primitive data types.
This code doesn't work. I get the following errors (in eclipse) that I can't seem to resolve:
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
Syntax error, insert ";" to complete BlockStatements
Duplicate local variable interest
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("input: ");
String input = in.next();
Integer interest = null; //to define interest
do
{
double interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
};
}
The variable interest is declared twice.
Here is a slightly cleaned up version of your code:
import java.util.Scanner;
public class DoWhile {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("balance: ");
int balance = in.nextInt();
System.out.print("interestRate: ");
double interestRate = in.nextDouble();
System.out.print("year: ");
int year = in.nextInt();
System.out.print("press 'N' to exit");
String input = in.next();
double interest = 0; //to define interest
do
{
interest = balance * interestRate / 100;
balance += interest;
year++; // print current balance
}
while (input.equals("N"));
System.out.println("interest: " + interest + "balance: " + balance + "year: " + year) ;
}
}
I am getting no errors from Eclipse but my console output is not what it should be. These are the 2 classes I am working on.
First Class
public class BankAccount
{
private double balance;
private double interestRate;
private double interest;
public BankAccount(double startBalance, double intRate)
{
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)
{
balance -= amount;
}
public void addInterest()
{
interest = balance * interestRate;
balance += interest;
}
public double getBalance()
{
return balance;
}
public double getInterest()
{
return interest;
}
}
Next Class
import java.util.Scanner;
import java.text.DecimalFormat;
public class Program2
{
public static void main(String[] args)
{
BankAccount account;
double balance = 500,
interestRate = 0.00125,
pay = 1000,
cashNeeded = 900;
Scanner keyboard = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat ("#0.00");
System.out.print("What is your account's starting balance?");
balance = keyboard.nextDouble();
System.out.print("What is your monthly interest rate?");
interestRate = keyboard.nextDouble();
account = new BankAccount(balance, interestRate);
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is "
+ formatter.format(account.getBalance()));
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
account.getInterest();
System.out.println("This month you have earned "
+ formatter.format( account.getInterest() )
+ " in interest.");
System.out.println("Now your balance is "
+ formatter.format( account.getBalance()));
}
}
Output which I am Getting:
What is your account's starting balance?
Output I should be getting:
What is your account's starting balance? 500
What is your monthly interest rate? 0.00125
How much were you paid this month? 1000
We will deposit your pay into your account.
Your current balance is 1500.00
How much would you like to withdraw? 900
This month you have earned 0.75 in interest.
Now your balance is 600.75
Scanners wait for input, until you give it information, it won't move on.
It is working totally fine.
I haven't modified anything in your code.
Actually I am thinking when the program is asking you to enter something, at that point you are not giving the input.
Try giving the input for example 500 when it asks What is your account's starting balance?
The problem
Design a SavingsAccount class that stores a savings account’s annual interest rate and balance. The class constructor should accept the amount of the savings account’s starting balance. The class should also have methods for subtracting the amount of a withdrawal, adding the amount of a deposit, and adding the amount of monthly interest to the balance. The monthly interest rate is the annual interest rate divided by twelve. To add the monthly interest to the balance, multiply the monthly interest rate by the balance, and add the result to the balance.
Test the class in a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number of months that have passed since the account was established. A loop should then iterate once for every month, performing the following:
Ask the user for the amount deposited into the account during the month. Use the class method to add this amount to the account balance.
Ask the user for the amount withdrawn from the account during the month. Use the class method to subtract this amount from the account balance.
Use the class method to calculate the monthly interest.
After the last iteration, the program should display the ending balance, the total amount of deposits, the total amount of withdrawals, and the total interest earned.
I keep getting one issue in the Main Program on line 22, that if I fix, it messes up a bunch of the code. Anyone know how I could go about fixing this?
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.*;
public class SavingsAccountMainProgram {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccountClass savingAccountClass = new SavingsAccountClass();
SavingsAccount savingsAccountClass = savingAccountClass.new SavingsAccount(
startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccountClass.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccountClass.withdraw(monthlyWithdrawl);
savingsAccountClass.addInterest();
interestEarned += savingsAccountClass.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $"
+ dollar.format(savingsAccountClass.getAccountBalance()));
}}
And the other program for this
import java.util.Scanner;
import java.io.*;
public class SavingsAccountClass {
class SavingsAccount {
private double accountBalance;
private double annualInterestRate;
private double lastAmountOfInterestEarned;
public SavingsAccount(double balance, double interestRate) {
accountBalance = balance;
annualInterestRate = interestRate;
lastAmountOfInterestEarned = 0.0;
}
public void withdraw(double withdrawAmount) {
accountBalance -= withdrawAmount;
}
public void deposit(double depositAmount) {
accountBalance += depositAmount;
}
public void addInterest() {
// Get the monthly interest rate.
double monthlyInterestRate = annualInterestRate / 12;
// Calculate the last amount of interest earned.
lastAmountOfInterestEarned = monthlyInterestRate * accountBalance;
// Add the interest to the balance.
accountBalance += lastAmountOfInterestEarned;
}
public double getAccountBalance() {
return accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public double getLastAmountOfInterestEarned() {
return lastAmountOfInterestEarned;
}
}
}
Also, would anyone know how I could submit a .class file like the teacher has requested?
Not sure why you have SavingsAccount as inner class. For what purpose?
Here I modified what you have shared and I think it answers the problem statement well
main method
public static void main (String arg[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccount.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccount.withdraw(monthlyWithdrawl);
savingsAccount.addInterest();
interestEarned += savingsAccount.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $" + dollar.format(savingsAccount.getAccountBalance()));
}
and, removed SavingsAccountClass and made SavingsAccount as the top level class
class SavingsAccount {
.
.
//everything as it is
}
I have an assignment for class and it's to go over inheritance and overloading and overriding methods. I think I did everything asked for in the instructions. However, I am a little confused about overloading and if I did it correctly. Actually not really sure how it works so I don't know if I did it all. So you do not have to read through the directions, my main question refers to, the directions that ask "Create two overloaded deposit methods in Account class such that one of them takes an integer value as the input parameter and the second one takes a double value as the input parameter." and I am not sure I did it correctly.
THANKS FOR ANY HELP!!!
Scott
Instructions available upon request.
Here is what I have....
ACCOUNT CLASS (super class)
//Account class
public class Account {
//create data fields
Scanner scan = new Scanner(System.in);
protected int id = 0;
protected double balance = 0;
protected double annualInterestRate = 0;
protected Date dateCreated;
public Account() {
dateCreated = new Date();
}
//constructor for account w/ with id and balance args.
public Account(int newID, double newBalance, double interestRate) {
dateCreated = new Date();
id = newID;
balance = newBalance;
annualInterestRate = interestRate;
}//end account method
//setter for account ID
public int setID(int newID) {
return id = newID;
}//end setID
//getter for account ID
public int getID() {
return id;
}//end getID
//setter for account balance
public void setBalance(double newBalance) {
balance = newBalance;
}//end setBalance
//getter for account balance
public double getbalance() {
return balance;
}//end method getBalance
//setter for accounts annual interest rate
public void setAnnualInterestrate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}//end setAnnualInterestRate
//getter for accounts annual interest rate
public double getAnnualInterestRate() {
return annualInterestRate;
}//end getAnnualInterestRate
//getter for date account was created
public Date getDateCreated() {
return dateCreated;
}//end getDateCreated
//calls the annual interest rate and divides by 12 to get the monthly rate
public double getMonthlyInterestRate() {
return (annualInterestRate) / 12;
}//end getMonthlyInterestRate
//method to make a withdrawal from account
public double withdraw(double withdrawAmount) {
balance -= withdrawAmount;
return withdrawAmount;
}
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
}
SAVINGS ACCOUNT CLASS
public class SavingAccount extends Account {
public SavingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double withdraw(double withdrawAmount){
if(balance >= withdrawAmount){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("You cannot be overdraw your Savings Account! \nThe max you will be allowed to withdraw is: " + balance + "\n");
setBalance(0);
return balance;
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
CHECKING ACCOUNT CLASS
public class CheckingAccount extends Account{
double overDraft = 5000;
public CheckingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double getOverdraft() {
return overDraft;
}
public void setOverdraft(double overdraft) {
overDraft = 5000;
}
public double withdraw(double withdrawAmount){
double balance = getbalance();
if(balance - withdrawAmount >= -overDraft){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("reach overdraf limit!");
setBalance(-overDraft);
return overDraft + getbalance();
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
TESTACCOUNT CLASS
import java.util.*;
public class TestAccount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int accID = 0;
double balance = 0;
double intRate = 0;
double withDraw = 0;
double Deposit = 0;
//savings account
System.out.println("Please enter the ID of the Savings Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Savings Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Savings Account: ");
intRate = scan.nextDouble();
scan.nextLine();
SavingAccount s = new SavingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Savings Account: ");
withDraw = scan.nextDouble();
s.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Savings Account: ");
Deposit = scan.nextDouble();
s.deposit(Deposit);
System.out.println("\nSavings Account Status:\n" + s);
//Checking account
System.out.println("\nPlease enter the ID of the Checking Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Checking Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Checking Account: ");
intRate = scan.nextDouble();
scan.nextLine();
CheckingAccount c = new CheckingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Checking Account: ");
withDraw = scan.nextDouble();
c.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Checking Account: ");
Deposit = scan.nextDouble();
c.deposit(Deposit);
System.out.println("\nChecking Account Status:\n" + c);
}
}
Also, is there anything else you would change to make the program better?
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
Yes, these are overloaded methods. You did it correctly.