I have a project that has to ask the user for a credit balance and a rate, and then output how much you would have to pay for the next 12 months if you payed the mininum payment(calculated by: balance * 0.03, and if thats lower than 10 then the mininum payment is $10).
I am cannot figure out why "balance * 0.03" will not increase in value of "minPay" as it loops.
import java.util.Scanner;
public class Project1Term2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println();
System.out.print("Enter credit card balance: ");
double balance = in.nextDouble();
System.out.print("Enter interest rate: ");
double interest = in.nextDouble();
interest = interest / 100;
for(int i = 0; i <= 12; i++)
{
Calculate out = new Calculate(balance, interest);
System.out.println(out.getNewValue());
balance = out.getNewValue();
}
}
}
class Calculate
{
private final double rate;
private double balance;
private double minPay;
private double newBalance;
Calculate(double balance, double rate)
{
this.balance = balance;
this.rate = rate;
}
double getNewValue()
{
if((balance * 0.03) < 10)
{
minPay = 10;
}
else
{
minPay = balance * 0.03;
}
newBalance = (balance - minPay) + (balance * rate);
return newBalance;
}
}
You are creating a new instance of Calculate on every loop. That´s wrong on many ways. One consequence is that you´re never incrementing minPay, as each instance is used only once.
If you are simply looking for an answer as to why your balance wasn't decreasing, the answer is that your logic was incorrect.
newBalance = (balance - minPay) + (balance * rate);
Should be:
newBalance = balance + (balance * rate) - minPay ;
You want to add the interest to the current balance, and then subtract whatever the minimum payment is. Running your program with that logic gave me:
Enter credit card balance: 100
Enter interest rate: .1
90.1
80.1901
70.2702901
60.340560390099995
50.4009009504901
40.45130185144059
30.49175315329203
20.522244906445323
10.542767151351768
0.5533099185031194
-9.446136771578377
-19.455582908349953
-29.475038491258303
You could also work on some better coding practices. For example, you shouldn't instantiate a new instance of the class every loop. Instead, continue to use the same class instance. You should also check to see if the balance is 0, for example the output I got from running your program allowed me to pay into the negatives.
Hope this helps, feel free to ask questions if it doesn't make sense.
Related
I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);
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?
Pretty new to Java, this is for an assignment. Basically what I'm trying to do is the user inputs the amount of hours they've worked, their hourly rate, and their straight time hours and the program outputs their net pay.
I can calculate the gross pay just fine but the assignment requires me to calculate net pay within a subclass by calling the calc_payroll and tax methods from the superclass but it keeps returning a value of zero. I thought maybe there was something wrong with my tax method so I tried returning the gross pay from the subclass but it still returned zero.
I'm really stumped here, can anyone help?
Superclass:
class Pay
{
private float hoursWorked;
private float rate;
private int straightTimeHours;
public double calc_payroll()
{
double straightTimePay = rate * straightTimeHours;
double excessPay = (rate * 1.33) * (hoursWorked - straightTimeHours);
double grossPay = straightTimePay + excessPay;
return grossPay;
}
public double tax(double a)
{
double taxRate;
double netPay;
if(a <= 399.99)
taxRate = 0.08;
else if(a > 399.99 && a <= 899.99)
taxRate = 0.12;
else
taxRate = 0.16;
netPay = a - (a * taxRate);
return netPay;
}
public void setHours(float a)
{
hoursWorked = a;
}
public float getHours()
{
return hoursWorked;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
straightTimeHours = a;
}
public int getHrsStr()
{
return straightTimeHours;
}
}
Subclass:
class Payroll extends Pay
{
public double calc_payroll()
{
Pay getVariables = new Pay();
double getGrossPay = getVariables.calc_payroll();
double finalNetPay = getVariables.tax(getGrossPay);
return finalNetPay; //This returns a value of zero
//return getGrossPay; This also returns a value of zero
}
}
Main Method:
import java.util.*;
class Assign2A
{
public static void main(String args[])
{
float userHours;
float userRate;
int userStraight;
Scanner userInput = new Scanner(System.in);
System.out.println("I will help you calculate your gross and net pay!");
System.out.println("Please enter the number of hours you have worked: ");
userHours = Float.valueOf(userInput.nextLine());
System.out.println("Please enter your hourly pay rate: ");
userRate = Float.valueOf(userInput.nextLine());
System.out.println("Please enter the number of straight hours required: ");
userStraight = Integer.parseInt(userInput.nextLine());
Pay object = new Pay();
object.setHours(userHours);
object.setRate(userRate);
object.setHrsStr(userStraight);
Payroll objectTwo = new Payroll();
System.out.println("========================================");
System.out.println("Your gross pay is: ");
System.out.println("$" + object.calc_payroll());
System.out.println("Your net pay is: ");
System.out.println("$" + objectTwo.calc_payroll());
System.out.println("Thank you, come again!");
}
}
Typical Output:
----jGRASP exec: java Assign2A
I will help you calculate your gross and net pay!
Please enter the number of hours you have worked:
500
Please enter your hourly pay rate:
25
Please enter the number of straight hours required:
100
========================================
Your gross pay is:
$15800.0
Your net pay is:
$0.0
Thank you, come again!
----jGRASP: operation complete.
Several issues. For one, you're creating a Payroll object:
Payroll objectTwo = new Payroll();
//.....
System.out.println("$" + objectTwo.calc_payroll());
Not giving it any value, and then are surprised when it holds a value of 0.
You should use one single object here, a Payroll object, not a Pay object, fill it with valid data, and call both methods on this single object.
Secondly, your Payroll class is completely wrong. You have:
class Payroll extends Pay {
public double calc_payroll() {
Pay getVariables = new Pay();
double getGrossPay = getVariables.calc_payroll();
double finalNetPay = getVariables.tax(getGrossPay);
return finalNetPay; // This returns a value of zero
// return getGrossPay; This also returns a value of zero
}
}
But it should not create a Pay object but rather use the super methods as needed. To better help you with this, you will have to tell us your complete assignment requirements because you're making wrong assumptions about the assignment, I believe.
Java Gurus,
Working on a class assignment and we are given a set of two programs. One calls on another to calculate interest rate, balances, etc for a bank account. What I am having problems with, is figuring out where I am supposed to input the variables we are given to get a successful compile for our program. Below are the two Java files we were given. I made the adjustments to correct all the purposeful errors in the code so everything compiles nicely so far.
public class BankAccount {
private double balance; // Account balance
private double interestRate; // Interest rate
private double interest; // Interest earned
/**
* The constructor initializes the balance
* and interestRate fields with the values
* passed to startBalance and intRate. The
* interest field is assigned to 0.0.
*/
public BankAccount(double startBalance, double intRate) {
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
/**
* The deposit method adds the parameter
* amount to the balance field.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* The withdraw method subtracts the
* parameter amount from the balance
* field.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
* The addInterest method adds the interest
* for the month to the balance field.
*/
public void addInterest() {
interest = balance * interestRate;
balance += interest;
}
/**
* The getBalance method returns the
* value in the balance field.
*/
public double getBalance() {
return balance;
}
/**
* The getInterest method returns the
* value in the interest field.
*/
public double getInterest() {
return interest;
}
}
Here is the Program2.java which is what we need to compile:
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay " + "into your account.");
account.deposit(pay);
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
// Withdraw some cash from the account.
System.out.print("How much would you like " + "to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned %bodyquot; + formatter.format( account.getInterest() )" +
" in interest.");
System.out.println("Now your balance is %bodyquot; + formatter.format( account.getBalance() ) )");
}
}
What I am required to enter is 500 for Starting Balance, 0.00125 for Monthly Interest Rate (Interest is compounded monthly in the code and pretty sure I know where to put this variable), 1000 Monthly Pay and 900 withdrawl amount. The end result should be $600.75.
Is all of my code there or do I need to declare the value of the variables Starting Balance, Interest Rate, Monthly Pay and Withdrawl Amount?
Please let me know if I am doing something wrong, or if the answer is smack in front of my face and I am just blind today.
Its a copy paste issue in your code.
Change From:
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
To:
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
Use below mentioned updated code.
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
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() ));
// Withdraw some cash from the account.
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
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() ) );
}
}
You're going to want to input those values either when you create your BankAccount class in your second program or at runtime. You could try something like this:
BankAccount account = new BankAccount(500, 0.00125)
And then input the rest of the values at runtime, or you could create local variables in Program 2 for everything and then create a new BankAccount using them as parameters.
Hope it helps.
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
}