I'm very very new, I'll try my best to word best I can (english is not my first language.) I hope my topic name is not confusing, right to the point.
public static double dogTotalFee(double totalFee)//calculate total fee (without tax)
{
double cost = 0.0;
double weight = 0.0;
int days = 0;
cost = 0.7;
return totalFee = cost * weight * days;
}//end dogTotalFee
public static double dogTax(double totalTax)//calculate tax
{double taxRate = 0.0;
double totalFee = 0.0;
return totalTax = totalFee * taxRate;
}//end dogTax
public static double dogTotalPrice(double totalPrice)
{
double totalFee = 0.0;
double totalTax = 0.0;
return totalPrice = totalFee + totalTax;
}//end dogTotalPrice
These values show up as zero, and the calculations don't add up.
totalFee = dogTotalFee(totalFee);
totalTax = dogTax(totalTax);
totalPrice = dogTotalPrice(totalPrice);
lPrice);
I'm mostly doing the math in the methods, I just can't seem to get the values to transfer. Thank you
Related
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;
}
Problem with my code for calculator - output values not correct
Here is my code, any response would be appreciated.
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
final value ends up being the same value as initial
Change this:
double monthlyInterest = ((interestRate/100)*(1/12));
to
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
You're trying to do integer division in floating-point context, so in monthlyInterest you are essentially multiplying interestRate / 100 with 0.
Add d with the numbers to convert them into double and keep the decimal value, this way -
double monthlyInterest = ((interestRate/100d)*(1/12d));
If you do 1/12 with integers, the output will be 0, but with 1/12d it will be 0.08333333333333333
Also, you can get rid of the extra parenthesis -
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;
Here's the textbook problem:
A certain bank offers 6.5% interest on savings accounts, compounded
annually. Create a table that shows how much money a person will
accumulate over a period of 25 years, assuming that the person makes
an initial investment of $1000 and deposits $100 each year after the
first. Your table should indicate for each year the current balance,
the interest, the new deposit, and the new balance.
This is my code. It is correct:
public void compoundAnnual() {
double investment = 1000;
int year = 25;
double newDeposit = 0;
double newBalance;
double interestRate = 6.5;
double interest;
double deposit = 0;
System.out.println("Year Interest New Deposit New Balance");
System.out.println("------------------------------------------------------");
for (int i = 1; i <= year; i++) {
if (i == 1)
{
newDeposit = investment;
}
newBalance = newDeposit * Math.pow((1 + (interestRate/100)), 1);
interest = newBalance - newDeposit;
System.out.printf("%1d %10.2f %20.2f %22.2f \n ", i, interest, newDeposit, newBalance);
newDeposit = newBalance + 100;
}
}
However, when finding the newBalance I am confused why
Math.pow((1 + (interestRate/100)), 1);
is correct.
Why wouldn't
Math.pow((1 + (interestRate), 1);
be correct if interestRate was set to 0.65? When I set interestRate equal to 0.65 the output for this is wrong and I don't understand why. Wouldn't they be the same thing?
Why wouldn't ... be correct if interestRate was set to 0.65?
Because 0.65 corresponds to 65% interest.
Try 0.065 (= 6.5 / 100).
(Note that this is nothing specific to programming, it's just arithmetic).
interestRate should be 0.065 in your case not 6.5, because 6.5/100=.065.If you hard code interestRate as 6.5 you won't get expected output.
Try giving
interestRate =.065
it will work fine.
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.
am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}
principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68
Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator