I am creating a small program, for a school assignment, in which people can input their running history (miles run, time elapsed) and see their potential 10K pace and marathon pace times. After the paces are displayed, a table of different paces is displayed.
I have a global variable (pace) which most of the calculations run with that needs to be altered inside a for loop but will not update for the calculations.
edit: I understand this program is poorly written and there's a lot of stuff that could be condensed. However, it works and will satisfy the parameters of the assignment. Inside the for loop, the variable "pace" needs to be increased by 30 with every iteration of the loop.
public class MarathonTime {
public static void main(String[] args) {
String name;
double distance;
int hours, minutes, seconds;
double pace;
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.print("What is your first name? ");
name = scanner.next();
System.out.print("How many miles did you run today? ");
distance = scanner.nextDouble();
System.out.print("How long did it take? Hours: ");
hours = scanner.nextInt();
System.out.print("Minutes: ");
minutes = scanner.nextInt();
System.out.print("Seconds: ");
seconds = scanner.nextInt();
pace = ((hours * 3600) + (minutes * 60) + seconds) / distance;
double marathonPace = pace * 26.2;
double tenKPace = pace * 6.2;
int paceMinutes, paceSeconds;
paceMinutes = (int) pace / 60;
paceSeconds = (int) pace % 60;
int marathonHours, marathonMinutes, marathonSeconds;
marathonHours = (int) marathonPace / 3600;
marathonMinutes = (int) (marathonPace % 3600) / 60;
marathonSeconds = (int) marathonPace % 60;
int tenKMinutes, tenKSeconds;
tenKMinutes = (int) tenKPace / 60;
tenKSeconds = (int) tenKPace % 60;
System.out.println("Hello " + name);
System.out.print("Your pace is "); timeFormatPace(paceMinutes, paceSeconds);
System.out.println();
System.out.print("At this rate your marathon time would be "); timeFormatMarathon(marathonHours, marathonMinutes, marathonSeconds);
System.out.println();
System.out.print("and your 10K time would be "); timeFormat10K(tenKMinutes, tenKSeconds);
System.out.println();
System.out.println("Good luck with your training!");
System.out.println();
for(int i = 1; i <= 10; i++){
if(i == 1) {
System.out.println("Pace \t\t 10K Time \t\t Marathon Time");
i++;
}
if(i == 2) {
System.out.println("------------------------------------------------------");
i++;
}
// input the tablePaces into the calcs and print them as the format
pace = (281 + (i*30));
if (i >= 3 && i <= 10) {
timeFormatPace(paceMinutes, paceSeconds); System.out.print("\t\t "); timeFormat10K(tenKMinutes, tenKSeconds); System.out.print("\t\t\t ");
timeFormatMarathon(marathonHours, marathonMinutes, marathonSeconds);
System.out.println();
}
}
}
I think this is what you're trying to do (very condensed):
public static void main(String[] args) {
int pace = 100; // or initialise to whatever
for(int i = 0; i < 10; i++) {
// do something
pace = pace + 30; // or equivalently, pace += 30
}
}
In future, try to reduce your problem to a minimal, complete and verifiable example. The process of doing this will often help you solve the problem yourself, but at the very least it makes it easy to for someone else.
Also, if you know your program is poorly written, fix it! Well written, concise, modular programs are much easier to reason about. Messy, complex code is difficult. You will thank yourself in less time spent debugging, and you'll get a better grade too.
Related
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 making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}
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
Im just learning how to code in Java, and I'm running into an error.
The line: "wage += (overtimeHours * basePay * 1.5);" if giving me some problems. The exact error is:
overtimeHours cannot be resolved to a variable
However, I have created the variable above with this line:
int overtimeHours = hours - 40;
So, what am I doing wrong here?
public class base_pay {
// create two methods in the base_pay class
// first method is pay, the second is main() to run the program
public static void pay(double basePay, int hours) {
if (basePay < 8.0) {
System.out.println("You must be paid at least $8.00/hr");
} else if (hours > 60) {
System.out.println("You cannot work more than 60 hr pr week");
} else {
// define what overtime is here
int overtime = 0;
if (hours > 40) {
int overtimeHours = hours - 40;
hours = 40; // Because anything over 40 is overtime .. if overtime was 50 hours than use 50
}
double wage = basePay*hours;
wage += (overtimeHours * basePay * 1.5);
System.out.println("Your total pay is: " + wage);
}
}
public static void main(String[] args) {
// going to run pay above, and see what happens
pay(8.5, 45);
}
}
Answered by own question. I defined the variable twice.
I figured it out as soon as I posted it. I defined the variable twice with "int" ... so I had to remove that.
I'm working on a program that will calculate the basic interest accrued on a certificate of deposit. The program asks for the amount of money invested and the term (up to five years). Depending on how many years their term is, is what determines how much interest is earned. I use an if/else statement to determine the rate of interest. I then use a loop to print out how much money is in the account at the end of each year. My problem is that when I run the program, the money is not counting.
Here is the entire code.
import java.util.Scanner;
public class CDCalc
{
public static void main(String args[])
{
int Count = 0;
double Rate = 0;
double Total = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("How much money do you want to invest?");
int Invest = userInput.nextInt();
System.out.println("How many years will your term be?");
int Term = userInput.nextInt();
System.out.println("Investing: " + Invest);
System.out.println(" Term: " + Term);
if (Term <= 1)
{
Rate = .3;
}
else if (Term <= 2)
{
Rate = .45;
}
else if (Term <= 3)
{
Rate = .95;
}
else if (Term <= 4)
{
Rate = 1.5;
}
else if (Term <= 5)
{
Rate = 1.8;
}
int count = 1;
while(count <= 5)
{
Total = Invest + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}
}
}
and here is the result I get with a 10 dollar investment, just to keep it simple, and a 5 year investment.
How much money do you want to invest?
10
How many years will your term be?
5
Investing: 10
Term: 5
Value after year 1: 10.18
Value after year 2: 10.18
Value after year 3: 10.18
Value after year 4: 10.18
Value after year 5: 10.18
My main problem is I dont know how to make it continually add the intrest onto the total. I'm not sure if I need to use a different loop or what. Any help would be appreciated.
Total = Invest + (Invest * (Rate) / (100.0));
You are not changing the value of Invest for each year, so it is not compounding. It is like you are getting .18$ of interest each year, retired from the account.
Change Total for Invest.
You need to add the investment interest to your total:
Total = Invest;
int count = 1;
while(count <= 5)
{
Total = Total + (Invest * (Rate) / (100.0));
System.out.println("Value after year " + count + ": " + Total);
count++;
}