(Java)Calculating the number of years to get to a specific balance - java

Here's the prompt:
There is a bank account that earns 5 percent interest per year. The initial account balance is $10000. Given a target balance (for example, $20000), return the number of years that it takes for the account balance to reach the target balance. The number of years should be an integer.
Here's my code:
public int getNumberOfYears(double targetBalance){
int years = 1;
for (double balance = 10000.0; balance <= targetBalance; years++) {
double multiplier = Math.pow(1.05, years);
balance *= multiplier;
}
return years;
}
When this runs, [multiplier] increases by the following pattern:
1.05^1 --> (1.05^1)^2 --> ((1.05^1)^2)^3 --> etc.
How do I fix my code so that [multiplier] increases by the following pattern:
1.05^1 --> 1.05^2 --> 1.05^3 --> etc?

When you do balance * Math.pow(1.05, years) that means you directly apply the increase for years, you want to go year by year, so just use the 1.05.
Also for that kind of problem, a while loop is prefered
public static int getNumberOfYears(double targetBalance) {
int years = 1;
double balance = 10000;
while (balance <= targetBalance) {
balance *= 1.05;
years++;
}
return years;
}

You don't need to increase the multiplier - every year carries the same interest, and you just need to keep multiplying by the same interest rate every year:
public int getNumberOfYears(double targetBalance) {
int years = 1;
double multiplier = 1.05;
for (double balance = 10000.0; balance < targetBalance; years++) {
balance *= multiplier;
}
return years;
}
EDIT:
As a side note, this can be solved without a loop, by extracting a log of both sides of the equation:
10000 * 1.05year = target
1.05year = target / 10000
log(1.05year) = log(target / 10000)
year * log(1.05) = log(target / 10000)
year = log(target / 10000) / log(1.05)
Or, in java:
public int getNumberOfYears(double targetBalance) {
double years = Math.log(targetBalance / 10000) / Math.log(1.05);
return (int) Math.ceil(year);
}

The following code will give you the answer in years. You can test it in excel by adding some formulas, the result is correct:
public class practice {
public static void main(String[] args) {
double interestRate = 0.05;
double initialAmount = 10000.00;
double targetValue = 20000.00;
int numYears = 0;
while(targetValue > initialAmount) {
initialAmount += (initialAmount * interestRate);
numYears++;
}
System.out.println("Year to hit target: " + numYears);
System.out.println("Final Amount: " + initialAmount);
}
}

You can use a while loop instead of for.
public int getNumberOfYears(double targetBalance){
int years = 1;
double balance = 10000.0;
while (1) {
if ( balance * 1.05 * years >= targetBalance) {
break;
}
else {
years++;
continue;
}
}
return years;
}
But you should consider on what happens to the interest earned on a year, is it being added to the current balance or added separately. If it is being added to the starting balance of the account consider following code.
public int getNumberOfYears(double targetBalance){
int years = 0;
double balance = 10000.0;
while (balance < targetBalance ) {
balance *= 1.05;
years ++;
}
return years;
}

Related

Java method for updating money with cents over 99

I am trying to create a method so that if the user enters a number of cents over 99, the updateMoney method will add dollars accordingly and then place the extra change once the cents goes under 100.
public void updateMoney(int cent) {
int addDollars = 0;
int change = 0;
if (cent > 99) {
for(int i = cent; i > 99; i -= 100)
{
addDollars += 1;
cent -= 100;
}
}
this.dollars = dollars + addDollars;
this.cents = cent;
}
public Money(int dol, int cent) {
if (cent < 0 || dol < 0) {
System.out.println("Invalid amount entered");
} else {
if (cent > 99) {
updateMoney(cent);
}
this.dollars = dol;
this.cents = cent;
}
}
This is the code I am currently working with.
I had originally tried a different method that ended up not working so I tried doing something like this instead but my outputs are still off.
In my driver I ran
Money money = new Money(15, 300); and the output was $15.00 when it should end up being $18.99
You should consider storing your dollars and cents in one long value. The following code takes your dollars and cents, combines them, adds the user's inputted cents correctly, and splits them up in dollars and cents again. But why not just keep them together all the time?
long dollarsWithCents = dollars * 100 + cents;
dollarsWithCents += parsedUserInput;
cents = dollarsWithCents % 100;
dollars = dollarsWithCents / 100;

I have a method compute(int months) but it does not iterate as I want it to be

This is my method compute(), which takes in the number of months:
public double compute(int months){
double balance = employee.getSalary();
double newBalance=0;
double monthlyInterest = (bankName.getInterestRate())/12;
double annualRaise = employee.getAnnualRaise();
if (months <=12){
for (int i = 1; i <= months; i++){
newBalance = (newBalance+balance)*(1+monthlyInterest);
}
return newBalance;
}
else{
int cycle = months/12;
while (cycle >0){
for (int i = 1; i <= 12; i++){
newBalance = (newBalance+balance)*(1+monthlyInterest);
}
cycle--;
months = months - 12; //remainder of months
balance = balance*(1+annualRaise/100); //new starting salary
}
for (int k = 1; k <= months; k++){
newBalance = (newBalance+balance)*(1+monthlyInterest);
}
return newBalance;
}
}
To give a context,
balance : is a fixed monthly pay an employee gets at the start of every month
monthly interest : is the interest rate that is computed on the balance in the employee's bank every month
annual raise : is the raise in employee's monthly pay at the start of a new year
An example of my input will be:
Bill Jobs 54000.0 0 0.012 13
where Bill Jobs is the employee with 54K as his balance, annual raise of 0% and 1.2% of annual interest rate from the bank, the duration of computation will be over 13 months. My desired output should be:
Bill Jobs: salary is 54K, annual raise is 0% has balance of 706933.71
where the balance of 706933.71 is computed when I call for the compute method, however I end up getting
Bill Jobs: salary is 54K, annual raise is 0% has balance of 705852.63
where his balance after 13 months is 705852.63 instead.
Refer below basic calculation for salary added with interest rate of 1.5% for every month. You can modify this according to your requirement.
import java.util.Scanner;
public class Salary {
public static void main(String[] args) {
double salary = 24000;
double interest = 1.5;
double total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the month = ");
int month = sc.nextInt();
if(month != 0 && month < 13){
for(int i=1; i <= month; i++){
salary += total;
total = (salary + (salary * (interest/100))) ;
}
System.out.println("salary with interest "+total);
}else{
System.out.println("Enter the month from 1-12");
}
}
}

Java compound interest calculation

my assignment is to calculate the number of years it takes to reach $5000 if you start with $2500 with 7.5% interest. The calculation should be 10 years, but it outputs 11 years. This might be a simple syntax error, but I've been trying to fix this for the past 2 hours with no luck.
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
accrued = principle * Math.pow(interest1, year);
year++;
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);
Try this :
final double principle = 2500.00;
double accrued = 0;
final double interest = 0.075;
int year = 0;
double interest1 = 1.0 + interest;
while (accrued < 5000.00)
{
year++;
accrued = principle * Math.pow(interest1, year);
}
System.out.printf("It would take %d years to reach at least $5000 if you start with $2,500 with 7.5%% compound interest.", year);

When compiling, I receive the error: "unreachable statement". How can I fix the issue?

public double Convertir(double Number) {
Number = nombre;
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
return annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}
With this code I am trying to convert a number written by the user,
which are days, into the number of years that it makes, the number of
weeks and the number of days. for example, number 365 should return 1
year 0 weeks 0 days.
return annee; returns annee so anything after this expression in the method won't get executed.
Perhaps you could return an Array instead:
public double[] Convertir(double Number) {
Number = nombre;
double[] all = new double[3];
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
all[0] = annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
all[1] = semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
all[2] = jour;
return all
}
or something similar. An ArrayList would probably be better...but it's the same general concept.
The code below return annee; won't be executed.
It looks like you want to return 3 values. You can only return 1 value, a double in this case.
Solution 1 (Global variables):
int annee, semaine, jour; //global variables
public void Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
annee = (int)(Number/365);
semaine = (int)((Number - annee * 365)/7);
jour = Number - annee * 365 - semaine * 7;
}
Solution 2 (return an array):
public int[] Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
int[] anneeSemaineJour = new int[3];
anneeSemaineJour[0] = (int)(Number/365);
anneeSemaineJour[1] = (int)((Number - anneeSemaineJour[0] * 365)/7);
anneeSemaineJour[2] = Number - anneeSemaineJour[0] * 365 - anneeSemaineJour[1] * 7;
return anneeSemaineJour;
}
You will then use it like this (Solution 2):
int[] resultat = convertir(822); // convertir(nombre) in your case I guess
System.out.println("Annee = " + resultat[0] + " Semaine = " + resultat[1] + " Jour = " + resultat[2]);
The problem is you have code (including another return) after a return statement. A return statement stops the function at that place and returns the value. Anything after that is unreachable.
Your code suffers from many problems.
Beside all what other have said (Everything below return won't be executed) you should be careful with your while loops, they are infinite loops:
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
If Number - 365 >= 0 then you're inside the while and you're adding 1 to annee, and this will not stop the loop since Number - 365 >= 0 will continue to be satisfied.
Same thing with your second loop.
"return" exits the method. If you want to return all of them (years, months, days) you can use an array. Your code had generally many mistakes, and similar operations were done on nombre (or Number as you had it) multiple times. I have tried to make to code runnable.
public double[] Convertir(double nombre) {
double[] yearsWeeksAndDays = new double[3];
double annee = 0;
double semaine = 0;
while (nombre >= 365) {
annee += 1; //this calculates the number of years
nombre -= 365;
}
yearsWeeksAndDays[0] = annee;
while (nombre >= 7) {
semaine = semaine + 1;
nombre -= 7;
}//this calculates the number of weeks
yearsWeeksAndDays[1] = semaine;
yearsWeeksAndDays[2] = nombre;
return yearsWeeksAndDays;
}
You need to wrap you 3 return values into a class and return that. Something like this ought to work:
public static void main(String[] args) {
System.out.println(convertir(365));
System.out.println(convertir(366.5));
System.out.println(convertir(456));
}
static class Duration {
int years;
int weeks;
double days;
#Override
public String toString() {
return years + " years, " + weeks + " weeks and " + days + " days.";
}
}
public static Duration convertir(double total) {
final Duration duration = new Duration();
duration.years = (int) (total / 365);
total = total % 365;
duration.weeks = (int) (total / 7);
total = total % 7;
duration.days = total;
return duration;
}
Output:
1 years, 0 weeks and 0.0 days.
1 years, 0 weeks and 1.5 days.
1 years, 13 weeks and 0.0 days.
Obviously it needs a little translation but French isn't my strong suit.
its throwing unrreachable code because compiler knows that when the controll reaches that return statement, then it would return and no more code would be executed.To solve this, what you could do is, either put the return statement in a condition block like i have shown below, but again this program wont return u the result you wanted. it will return only the year. if you want the entire result ie. number of years + number of weeks + number of days i would suggest you to make the entire answer to a single string and return.
public double Convertir(double Number) {
// Number = nombre;
double annee = 0;
double semaine = 0;
double jour = 0;
while ((Number - 365) >= 0) {
annee += 1; // this calculates the number of years
}
if (annee > 0) {
return annee;
}
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}// this calculates the number of weeks
if (semaine > 0)
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}

Working out taxable income Java

I have just finished a Java test at university and I know that I have answered a particular question wrong and would just like some help / clarification please?
The question was as follows:
implement a method that takes someones income and works out the tax.
If that person earns less than 7500 then tax = 0.
If that person earns between 7501 and 45000 then tax = 20%, less the 7500, which is tax free.
Finally, if that person earns above 45001 then tax = 40%, less the income in the 20% bracket, and then less the 7500 which is tax free.
As time was running short, I just did a basic if else statement showing income and tax brackets, example below.
public static double incomeTax(double income){
if(income <= 7500){
income = income * 0;
}
else if(income >= 7501 && income <= 45000){
income = income * 0.8;
}
else(income >= 45001){
income = income * 0.6;
}
return income;
}
I know that the code is not correct, no where near, but as it was coming to the end of the test I gave it a go in a hope just to get a mark for the if else statements.
I would really appreciate any help here.
Thank you.
After great feedback, this is what I came back with (with a LOT of help!!:] )...
import java.util.Scanner;
public class TaxableIncome
{
public static void main(String[] args){
netIncome();
}
public static double netIncome() {
double income = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter income: ");
income = in.nextDouble();
System.out.println();
double tax1 = 0;
double tax2 = 0;
double totalTax = tax1 + tax2;
// high income bracket
if (income > 45000) {
double part1 = income - 45000; // part = income - 45000
tax1 += part1 * 0.4; // tax = tax + part * 0.4
System.out.println("High Tax Band - Greater than 45000: " + tax1);
}
// medium income bracket
if (income > 7500) {
double part2 = income - 7500;
tax2 += part2 * 0.2;
System.out.println("Medium Tax Band - Greater than 7500: " + tax2);
}
System.out.println("Total Tax = " + (tax1 + tax2));
// tax for low income is zero, we don't need to compute anything.
return totalTax;
}
}
A simple answer would be as this:
public static double netIncome(double income) {
double tax = 0;
// high income bracket
if (income > 45000) {
double part = income - 45000;
tax += part * 0.4;
income = 45000;
}
// medium income bracket
if (income > 7500) {
double part = income - 7500;
tax += part * 0.2;
}
// tax for low income is zero, we don't need to compute anything.
return tax;
}
This way you calculate the tax for each tax bracket and sum them.
I see nothing wrong with the logic. The main issue you had was you just need to return the income tax, not the total income. So the value you needed to return was income*whateverPercentTax.
Also, I would've tried:
if(income < 7001){
}else if(income >=45001){
}else{}
But that is just me.
I would start with something like this:
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
Note that income is an int due to a peculiarity of the tax calculation in the UK - it also solves the problem with the unspecified cases between 7500.01 and 7500.99 inclusive.
A better solution would extract constants for all the magic numbers. An even better solution would generalise the bands and rates into a table so that they can be changed easily.
A complete answer might include test cases like this:
import org.junit.Assert;
import org.junit.Test;
public class TestTax
{
public static final double DELTA = 0.1;
#Test
public void testTax() {
Assert.assertEquals(0.0, incomeTax(-3000), DELTA);
Assert.assertEquals(0.0, incomeTax(0), DELTA);
Assert.assertEquals(0.2, incomeTax(7501), DELTA);
Assert.assertEquals(3000.0, incomeTax(22500), DELTA);
Assert.assertEquals(7500.0, incomeTax(45000), DELTA);
Assert.assertEquals(7500.4, incomeTax(45001), DELTA);
Assert.assertEquals(25500.0, incomeTax(90000), DELTA);
}
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
}
You'd have to tax things in bands. Dirty (untested) code:
public static double incomeTax(double income){
double tax = 0;
if(income > 7500){
tax += Math.min(45000-7500, income-7500)*.2;
}
if(income > 45000){
tax += (income-45000)*.4;
}
return tax;
}
You need to attempt to apply the tax rates more than once. Your code only hits one tax bracket. If I made 100k, I would have been taxed at 40% for the whole 100k. Here is something I came up with quickly.
public static double incomeTax(double income)
{
double tax = 0.0;
int midLevel = 7500;
int highLevel = 45000;
if (income <= 7500)
{
// Could early exit at this point and return already set tax
tax = 0.0;
}
if (income > midLevel)
{
// Find range of income > 7500, less than 4500. 37499 max
double taxableIncome = Math.min(income - midLevel, highLevel - midLevel - 1);
tax += taxableIncome * 0.2;
}
if (income > highLevel)
{
// Income above 45k
double taxableIncome = income - highLevel;
tax += taxableIncome * 0.4;
}
return tax;
}
You could try this, just copy your income brackets in the bracket array. Make sure you have infinity in bracket array and start with 0 in rate array.
import java.util.Scanner;
import java.text.DecimalFormat;
class IncomeTaxWithBrackets {
public static void main(String[] args) {
double infinity = Double.POSITIVE_INFINITY;
double [] bracket = {0, 7565, 25903, 54987, 121121, 567894, infinity};
double [] rate = {0, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35};
// bracket[0] to bracket[1] are assigned rate[1]
double income = 0;
double tax = 0;
System.out.print("\nPlease enter your income: ");
Scanner keyboard = new Scanner (System.in);
DecimalFormat dollar = new DecimalFormat ("$#,##0.00");
income = keyboard.nextDouble();
int x,i;
for (i=0; i <= 5; i++) {
if (income > bracket[i] && income <= bracket[i+1]) {
for (x=0; x<i; ++x) {
tax = tax + (bracket[x+1] - bracket[x]) * rate[x+1];
}
tax = tax + (income - bracket[i]) * rate[i+1];
}
}
System.out.println("\nWith a taxable income of "+dollar.format(income)+", your personal income tax is "+dollar.format(tax));
}
}
Let me know what you think.

Categories

Resources