I have a task here: Define a class PayPerView with method moviefee() that calculates the monthly charges for movies rented. The method should take one argument representing number of movies rented and return the fee as a double.
The rental fee fee is $6.99 per movie. Preferred customers that rent more than 10 per month get a discount of 5%.
Here's my code so far:
public class PayPerView {
public static void main(String [] args){
}
public static double moviefee(int n){
double fee = 6.99;
double total= n*fee;
System.out.println("Your balance due this month is" + total);
//return 6.99*n * ((n>10) ? 0.95:1);
}}
I know it's awful, I'm sorry and you can ignore that last line of code I commented out because I'm going to redo it and turn it into an if statement. I thought maybe I should use an array, but I can't right? Because I don't know how many movies are/will be rented? Should I use an arraylist for the number of movies rented?
Actually that line you commented out looks pretty much exactly what you are trying to do anyway. Is there something particularly wrong with it?
If you really need to output the result on the console...
final double fee = 6.99;
double total = n * fee * (n > 10 ? .95 : 1.0);
System.out.println("Your balance due this month is" + total);
return total;
I don't see why you'd use an ArrayList if you don't have any data to put into it.
You'd probably want to try something along these lines:
double total = n * fee;
if (n > 10) {
total *= 0.95;
}
I also see that you wanted to use the ternary operator, so you could replace the above code block with
double total = n * fee * (n > 10 ? 0.95 : 1.0);
Your on the right track
public static double moviefee(int n){
double fee = 6.99;
double total;
if(n <= 10){
total= n*fee;
}
else{
total= n*fee - (n*fee*0.05); //5 percent discount
}
System.out.println("Your balance due this month is" + total);
return total;
}
Edit: added double total;
Related
I am trying to do on the java assignment and the scenario is as follows:
A sales tax of 7% is levied on all goods and services consumed. It is also mandatory that all the price tags should include the sales tax. For example, if an item has a price tag of $107, the actual price is $100 and $7 goes to the sales tax.
Write a program using a loop to continuously input the tax-inclusive price (as "double"); compute the actual price and the sales tax (in "double"); and print the results rounded to 2 decimal places. The program shall terminate in response to input of -1; and print the total price, total actual price, and total sales tax.
However, when I try to compute the sales tax, instead of showing this:
Enter·the·tax-inclusive·price·in·dollars·(or·-1·to·end): 107
Actual·Price·is: $100.00
Sales·Tax·is: $7.00
My calculation shows this:
Enter the tax-inclusive price in dollars (or -1 to end): 107
Actual price is $99.51
Sales Tax is: $7.49
I am not sure what's wrong with my coding.
import java.util.Scanner;
public class SalesTax{
public static void main(String[] args) {
// Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1; // Terminating value for input
// Declare variables
double price, actualPrice, salesTax; // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; // to accumulate
// Read the first input to "seed" the while loop
Scanner in = new Scanner(System.in);
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
while (price != SENTINEL) {
// Compute the tax
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
// Accumulate into the totals
totalPrice = actualPrice + salesTax;
totalActualPrice = actualPrice + actualPrice;
totalSalesTax = salesTax + salesTax;
// Print results
System.out.println("Actual price is $" + String.format("%.2f",actualPrice));
System.out.println("Sales Tax is: $" + String.format("%.2f",salesTax));
// Read the next input
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
// Repeat the loop body, only if the input is not the sentinel value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
// print totals
System.out.println("Total price is: " + String.format("%.2f",totalPrice));
System.out.println("Total Actual Price is: " + String.format("%.2f",totalActualPrice));
System.out.println("Total sales tax is: " + String.format("%.2f",totalSalesTax));
}
}
Any help would be appreciated. Thank you!
You're wrong with these two lines:
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
You're calculating the sales on the already-saled price, try following me:
Your price is the composition of the actualPrice and the tax on actualPrice:
price = actualPrice + SALES_TAX_RATE * actualPrice
so you can mathematically do the following passages:
price = actualPrice * (1 + SALES_TAX_RATE)
actualPrice = price / (1 + SALES_TAX_RATE)
So, try changing the assigment of actualPrice, then calculate the tax on your actualPrice:
salesTax = SALES_TAX_RATE * actualPrice;
You should calculate actual price first and with the help of that calculate sales tax rate
and instead of using this
salesTax = SALES_TAX_RATE * price; actualPrice = price - salesTax;
calculate using this:
actual_price = price / 1.07; tax_price = price - actual_price;
1.07 came from dividing tax % with 100 and adding 1 to it(you can do this to any amount of %)
I came across something similar and used this logic. You need to divide the sales tax by 100 like 7/100 with 7 being the percentage of your tax variable or you can multiply by .01 then take the result of that and add it to your variable's total value. 1% is .01 of 100%. So 7% would be .07 multiplied by your variable and added to the total you are trying to calculate. If you want precision and not rounded to the nearest integer then just set parameters on the Math.round function or don't even use it at all.
public static void solve(double meal_cost, int tip_percent, int tax_percent) {
double tip = Math.round((tip_percent * .01) * meal_cost);
double tax = Math.round((tax_percent * .01) * meal_cost);
int total_cost = (int)(meal_cost + tip + tax);
System.out.println(total_cost);
}
The problem is your sales tax calculation, try:
final double SALES_TAX_RATE = 7;
salesTax = price / (100 + SALES_TAX_RATE) * SALES_TAX_RATE;
My problem is: Suppose that one credit hour for a course is $100 at a school and that rate increases 4.3% every year. In how many years will the course’s credit hour costs tripled?
The rewrote this simple code many times, but just can't seem to get it.
I think i'm going about this the wrong way..
import java.util.Scanner;
public class MorenoJonathonCreditHourCostCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double cost = 100;
int years=0;
double sum=200;
double total;
while (cost >= sum) {
total = cost + 4.03;
++years;
}
System.out.println("The tuition will double in " + years + " years");
}
}
A rate increase of 4.3% means that in every step, the value is 4.3% bigger than the previous value. This can be described by the following formula:
V_n+1 = V_n + (V_n * 4.3%)
V_n+1 = V_n + (V_n * 0.043)
V_n+1 = V_n * (1 + 0.043)
V_n+1 = V_n * 1.043
In Java this boils down to simply cost *= 1.043;
You first stated " In how many years will the course’s credit hour cost tripled", but in your program you actually check for when it has doubled.
I assume you want to calculate the triple cost, so your program should now look something like this:
public static void main(String[] args) {
double cost = 100;
double tripleCost = 3 * cost;
int years = 0;
while(cost < tripleCost) {
cost *= 1.043;
years++;
}
System.out.println("It took " + years + " years.");
}
Which gives the following output:
It took 27 years.
I am not sure why you are adding to cost since it is a multiplication function:
FV(future value) = PV(present value) (1+r)^n
300 = 100(1.043)^n where you are looking for 'n'
Set up a while loop that operates while the future value is under 300 and adds to 'n'.
I am currently trying to develop a compound interest calculator that includes monthly contributions. I have successfully been able to get the compound interest calculation working without the monthly contributions using the following line of code, but cannot figure out what the formula should be when adding monthly contributions.
double calculatedValue = (principalValue * Math.pow(1 + (interestRateValue/numberOfCompoundsValue), (termValue * numberOfCompoundsValue)));
When trying to get the calculated value with contributions I changed the way this is done. See the following code how I approached this.
//The starting principal
double principalValue = 5000;
//Interest rate (%)
double interestRateValue = 0.05;
//How many times a year to add interest
int numberOfCompoundsValue = 4;
//The number of years used for the calculation
double termValue = 30;
//The monthly contribution amount
double monthlyContributionsValue = 400;
//How often interest is added. E.g. Every 3 months if adding interest 4 times in a year
int interestAddedEveryXMonths = 12/numberOfCompoundsValue;
//The total number of months for the calculation
int totalNumberOfMonths = (int)(12 * termValue);
for(int i = 1; i <= totalNumberOfMonths; i++)
{
principalValue += monthlyContributionsValue;
if(i % interestAddedEveryXMonths == 0)
{
principalValue += (principalValue * interestRateValue);
}
}
I figured this should do what I am after. Every month increase the principal by the contribution amount and if that month equals a month where interest should be added then calculate the interest * the interest rate and add that to the principal.
When using the values above I expect the answer $355,242.18 but get $10511941.97, which looks better in my bank account but not in my calculation.
If anyone can offer me some help or point out where I have gone wrong that would be much appreciated.
Thanks in advance
Your problem is here:
principalValue += (principalValue * interestRateValue);
You're adding a full year's interest every quarter, when you should be adding just a quarter's interest. You need to scale that interest rate down to get the right rate.
Here's an example:
class CashFlow {
private final double initialDeposit;
private final double rate;
private final int years;
private final double monthlyContribution;
private final int interestFrequency;
CashFlow(double initialDeposit, double rate, int years,
double monthlyContribution, int interestFrequency) {
if ( years < 1 ) {
throw new IllegalArgumentException("years must be at least 1");
}
if ( rate <= 0 ) {
throw new IllegalArgumentException("rate must be positive");
}
if ( 12 % interestFrequency != 0 ) {
throw new IllegalArgumentException("frequency must divide 12");
}
this.initialDeposit = initialDeposit;
this.rate = rate;
this.years = years;
this.monthlyContribution = monthlyContribution;
this.interestFrequency = interestFrequency;
}
public double terminalValue() {
final int interestPeriod = 12 / interestFrequency;
final double pRate = Math.pow(1 + rate, 1.0 / interestPeriod) - 1;
double value = initialDeposit;
for ( int i = 0; i < years * 12; ++i ) {
value += monthlyContribution;
if ( i % interestFrequency == interestFrequency - 1 ) {
value *= 1 + pRate;
}
}
return value;
}
}
class CompoundCalc {
public static void main(String[] args) {
CashFlow cf = new CashFlow(5000, 0.05, 30, 400, 3);
System.out.println("Terminal value: " + cf.terminalValue());
}
}
with output:
run:
Terminal value: 350421.2302849443
BUILD SUCCESSFUL (total time: 0 seconds)
which is close to the $355k value you found.
There are a number of different conventions you could use to get the quarterly rate. Dividing the annual rate by 4 is a simple and practical one, but the pow(1 + rate, 1 / 4) - 1 method above is more theoretically sound, since it's mathematically equivalent to the corresponding annual rate.
After some brief testing I've come to the conclusion that either you have:
miscalculated the value you want ($355,242.18)
OR
incorrectly asked your question
The calculation you've described that you want ($5000 start + $400 monthly contributions for 30 years + interest every 3 months) is found by the code you've provided. The value that it gives ($10,511,941.97) is indeed correct from what I can see. The only other suggestions I can offer are to only use double if you need to (for example termValue can be an int) AND when ever you know the value is not going to change (for example interestRateValue) use final. It will help avoid any unforeseen error in larger programs. I hope this helps you figure out your interest calculator or answers any questions you have.
static void Main(string[] args)
{
double monthlyDeposit;
double rateOfInterest;
double numberOfCompounds;
double years;
double futureValue = 0;
double totalAmount = 0;
Console.WriteLine("Compound Interest Calculation based on monthly deposits");
Console.WriteLine("Monthly Deposit");
monthlyDeposit = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Rate Of Interest");
rateOfInterest = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of Compounds in a year");
numberOfCompounds = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Number of year");
years = Convert.ToDouble(Console.ReadLine());
futureValue = monthlyDeposit;
for (int i = 1; i <= years * 12; i++)
{
totalAmount = futureValue * (1 + (rateOfInterest / 100) / 12);
if (i == years * 12)
futureValue = totalAmount;
else
futureValue = totalAmount + monthlyDeposit;
}
Console.WriteLine("Future Value is=" + futureValue);
Console.ReadLine();
}
//Output
Compound Interest Calculation based on monthly Deposits
Monthly Deposit
1500
Rate Of Interest
7.5
Number of Compounds in a year
12
Number of year
1
Future Value is=18748.2726237313
I need to calculate the monthly compounding interest in a savings account that is getting a monthly deposit. The variables I have to work with:
monthly savings ( Eg. I deposit $125.75 each month)
months (Eg. I deposit the same for 15 months)
APR (the ANNUAL interest is 5.65%)
Now I need to calculate the total savings amount, which for the given numbers here, the final answer should be $1958.88.
In essence, I am working with A = P(1 + r/12)^(12*t), where P is the amount I deposit * months, r is the APR, and t is the months/12 to get the "how many years"
The catch here is that I can not use the math.pow() as a requirement on the assignment, so my best guess is that I am to calculate it with a for/while loop similar to the following:
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double totalSavings = 0;
while (monthCount < months)
{
totalSavings += monthlySavings + (1+APR/12/100);
mothCount++;
}
System.out.printf("Your total savings will be $%.2f\n", totalSavings);
}
The above code is NOT the correct solution, but its the closest i've come. The problem is that I am applying the interest to the monthly savings each time before it accumulates to the total. eg. it adds 125.75*interest for 15 deposits. What it SHOULD do is start with 125.75*interest then add 125.75, and then take the interest of the amount you have total so far, then add 125.75 and take the interest of the total amount again, and so on for the amount of months.
This is probably a lot easier than I am making it out to be, but I have tried for hours with adding different placeholder variables, but I am lacking some crucial concept, please help!
A loop for the number of months
for (int monthNumber = 0; monthNumber < numberOfMonths; monthNumber++)
{
}
then for each each month, add the interest then add the monthly savings. In that order, the other way around you end up with interest on money you just deposited, which is wrong.
totalSavings *= (APR / 12 / 100); //Although I would have separate variable for this
totalSavings += monthlySavings;
you don't really need to keep a month count but I prefer for loops.
After re-reading my question, I had an epiphany.. As I originally thought, the answer was a lot easier than I was making it out to be.
public static void main(String[] args)
{
double monthlySavings = 125.75;
double APR = 5.65;
int months = 15;
int monthCount = 0;
double placeHolder = 0;
double totalSavings = 0;
while (monthCount < months)
{
placeHolder += monthlySavings;
totalSavings = placeHolder * (1+APR/12/100);
placeHolder = totalSavings;
monthCount++;
}
System.out.printf("Your total savings will be $%.2f", totalSavings);
}
I've recently embarked into Java programming and consider myself a programming novice. It seem that I'm having an issue with my source code arithmetic. I have verified all the nested if-else statements and they all work up to the final else statement's arithmetic. It doesn't calculating correctly I have set the arithmetic up just as the above if-else statements.
the else statement is suppose to subtract 40 from the amount and then apply 1 percent charge. I have tried for the else statement fee = ((checkAmount - 40) * .01) and fee = ((checkAmount * .01) - 40)
This is just an exercise from the book
import java.util.Scanner;
public class ServiceCharge {
public static void main(String[] args)
{
double checkAmount;
double fee;
Scanner kb = new Scanner(System.in);
System.out.println("I will calulate the service charge to cash your check");
System.out.print("Enter amount of check: $");
checkAmount = kb.nextDouble();
if (checkAmount > 0)
{
if (checkAmount <= 10)
{
fee = -1;
System.out.println("$1 service charge");
checkAmount = checkAmount + fee;
System.err.println("You have " + checkAmount + " left after service charge.");
}
else if ((checkAmount > 10) && (checkAmount <= 100))
{
System.out.println("There will be a 10 percent charge.");
fee = (checkAmount * .10);
checkAmount = checkAmount - fee;
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n" , checkAmount);
}
else if ((checkAmount > 100) && (checkAmount <= 1000))
{
System.out.println("There will be a $5 charge plus 5 percent");
fee = ((checkAmount - 5) * .05);
checkAmount = (checkAmount - fee);
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n", checkAmount);
}
else
{
System.out.println("$40 processing fee plus 1 percent");
fee = ((checkAmount - 40) * .01);
checkAmount = (checkAmount - fee);
System.out.printf("Processing fee: $%.2f\n" , fee);
System.out.printf("Check amount: $%.2f\n" , checkAmount);
}
System.out.println("Thanks for using Service Charger." + "\nGood bye");
}
}
}
For the last else statement, it seems a bit off from the rest of your statements. You're using "hold" to store the original checkAmount value, then modifying checkAmount to be the fee for the first three statements. You should model the last one like the one before it. The checkAmount should be checkAmount = (checkAmount * .01) + 40, then hold - checkAmount should return the value you're looking for. By having checkAmount = checkAmount - 40, the last line is returning hold (checkAmount) - (checkAmount - 40), which will always return 40.
System.out.println("$40 processing fee plus 1 percent");
fee = ((checkAmount - 40) * .01);
That's not a 40 dollar fee + 1 percent. That's a fee of slightly less than 1 percent; it's as if you cash out the first 40 dollars for free, and then apply a 1 percent charge to the rest.
Assuming the 1% charge applies to the whole check, rather than what's left after subtracting 40 dollars, the correct expression for the fee is
fee = 40 + 0.01*checkAmount;
Actually, you wanted to only charge the 1% fee over the check amount less the $40 dollar fixed fee according to your original expression, so the expression should be:
fee = 40 + (checkAmount - 40) * .01;
There's a lot of duplication in your code, which makes it harder to see what's going on, and if you decide to change - for example - the message that you want to show to the user, you now need to change it in 4 locations, and there's a big change that you forget to do it somewhere, or that you make a typo.
One of the goals of good programming is to avoid duplication as much as possible.
public class ServiceCharge {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("I will calulate the service charge to cash your check");
System.out.print("Enter amount of check: $");
double checkAmount = kb.nextDouble();
if (checkAmount > 0) {
double fee;
String feeMessage;
if (checkAmount <= 10) {
fee = 1;
feeMessage = "$1 service charge";
} else if ((checkAmount > 10) && (checkAmount <= 100)) {
feeMessage = "10 percent charge.";
fee = (checkAmount * .10);
} else if ((checkAmount > 100) && (checkAmount <= 1000)) {
feeMessage = "$5 charge plus 5 percent";
fee = 5 + ((checkAmount - 5) * .05);
} else {
feeMessage = "$40 processing fee plus 1 percent";
fee = 40 + ((checkAmount - 40) * .01);
}
checkAmount = checkAmount - fee;
System.out.printf("Fee structure: " + feeMessage);
System.out.printf("Processing fee: $%.2f\n", fee);
System.out.printf("Check amount: $%.2f\n", checkAmount);
System.out.println("Thanks for using Service Charger.\nGood bye");
}
}
}
The next step you may want to look into is to decompose your program functionally into functions. For example, the part where you ask for the amount, the part where you do the calculation, and the part where you show the result, are three very distinct parts. Each of those three you may want to change separately - you may want to get the input from a file or from a web request, and you may want to store use the result in another calculation rather than show it to the user.
So these could go into separate functions.
And then you could think about object decomposition - perhaps we're talking here about a CheckCashAction object that has properties for checkAmount, fee, feeStructure and payoutAmount.
Etc.
The nice thing then is that you can look at each of the steps separately and test them in isolation, which makes it easier to pinpoint bugs and to maintain the code.