trouble with while loop java - java

This is extremely simple and I'm sorry I am having trouble getting this to work. It works when I remove the while loop with just the processing, but I'm not sure what I'm doing wrong with the whileloop. Any suggestions?
/*Cobalt
60, a radioactive form of cobalt used in cancer therapy, decays or
dissipates over a period of time. Each year, 12 percent of the
amount present at the beginning of the year will have decayed. If
a container of cobalt 60 initially contains 10 grams, create a
Java program to determine the amount remaining after five years. */
public class Cobalt {
public static void main(String[] args) {
//dec
double CInitial = 10.0;
double decay = .12;
double CUpdatedA, CUpdatedB;
//proc
int years = 0;
while (years < 5);
{
CUpdatedA = CInitial * decay;
CUpdatedB = CInitial - CUpdatedA;
years++;
}
//out
System.out.println("the amount of cobalt left after 5 years is"
+ CUpdatedB);
}
}

In your code, read this line carefully :
while (years < 5);
There is a semicolon at the end, which means that this statement is finished.
You might ask, "why doesn't the bracket cause an error?"
The brackets mean a section, it does not affect the code.
The way to make this work is to remove the colon.
ALSO,
You need to initiailize your variables or the compilers will show
variable CUpdatedB might not have been initialized
(write CUpdatedA, CUpdatedB = 0)

Besides, the while loop issue i.e, removing of semicolon. You don't seem to be getting correct answer because at the end of every loop your CInitial is not updated with the value after decay during that year.
Here am resetting CInitial with CUpdatedB as a last statement in while loop.
public class Cobalt {
public static void main(String[] args) {
//dec
double CInitial = 10.0;
double decay = 0.12;
double CUpdatedA = 0, CUpdatedB = 0;
//proc
int years = 0;
while (years < 5)
{
CUpdatedA = CInitial * decay;
CUpdatedB = CInitial - CUpdatedA;
CInitial = CUpdatedB;
years++;
}
//out
System.out.println("the amount of cobalt left after 5 years is: " + CUpdatedB);
}
}
Output: the amount of cobalt left after 5 years is: 5.277319168
I hope thats the answer your expecting.

Related

Loops, which to use, and how to stop it

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'.

Programming a series

I'm having trouble with my exercise.
I'm supposed to write a program, which calculates this series and and which gives out the value every loop. The series also needs to break if the change of the series value is lower than 10^-5 in a loop.
I hope my explanation was understandable so far.
This is what I came up with:
public static void main(String [] args) {
double sum = 0;
double summand;
double k = 1;
do
{
summand = 1.0/Math.pow(k, 2);
sum = 6 * (sum + summand);
k++;
}
while (summand > 1E-5);
System.out.println(sum);
}
Now I need help, since I'm very new to Java and I have no clue whether this is right or wrong.
Thanks for your help in advance!
Your sum line is wrong - as written you're cumulatively multiplying your value so far in every iteration, whereas you should be able to see from the original question posed that the factor of six only applies once.
You need:
sum = sum + 6 * summand
or alternatively leave the multiplication by 6 until after the summation, which more closely matches the given formula:
do {
summand = 1.0 / (k * k);
sum += summand;
} while (summand > 1e-5);
sum *= 6.0;
Just move the System.out.println(sum) inside the loop.
public static void main(String [] args) {
double sum = 0;
double summand;
double k = 1;
do
{
summand = 1.0/Math.pow(k, 2);
sum = 6 * (sum + summand);
k++;
System.out.println(sum); // <-- here it's right
}
while (summand > 1E-5);
}
That way it will be printed for every iteration of the loop.

java compound interest with contributions formula

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

New to java, don't understand why my while loop program will not run

Here is the problem I am trying to solve.
"Mexico's population is 62 million and is growing at the annual rate of 7%. The United States' current population is 280 million and is growing at the annual rate of 2%. If these two countries were to maintain their current rates of growth, in how many years will Mexico's population be more than half that of the United States? Your program should answer this question."
okay so this is the code that I have so far. when I run the program I get this error.
Not really sure how to fix it. Can anyone help out? :/
import java.util.Scanner;
public class Whatever {
public static void main (String [] args){
Scanner in = new Scanner (System.in);
int mex = 62000000;
int usa = 280000000;
int years = 0;
double t = 0 ;
while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
{
t++;
years = t;
if (mex > (usa * 0.5));
break;
}
System.out.println ("Mexicos population is half of America in " + years + "years");
}
}
EDIT
for anyone wondering I ended up getting the code to work. this is the code.
import java.util.Scanner;
public class Whatever {
public static void main (String [] args){
Scanner scan = new Scanner (System.in);
double mex = 62000000;
double usa = 280000000;
double years = 0;
while(mex <= usa/2)
{
years++;
mex = mex * 1.07;
usa = usa * 1.02;
}
System.out.println ("Mexicos population is half of America in " + years + " years ");
}
}
mex is an integer.
I think you were trying to multiply.
Use mex * (Math.pow(1.07, t), if you want to multiply.
Your problem is here:
while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
Putting parentheses right after a variable signals to Java that you're trying to call the function with that name (in this case mex and usa). What you're actually trying to do is multiply those values, so you need asterisks in there:
while(mex*(Math.pow(1.07, t)) <= usa*(Math.pow(1.02, t)))
In your code, you define several variables:
int mex = 62000000;
int usa = 280000000;
int years = 0;
double t = 0 ;
However, you try to use these as functions:
while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
In Java, these variables are used as arguments for functions; not the other way around!
You have applied parenthesis to the "mex" expression in your while loop (as if it were a function), where "mex" is just a regular variable. Same thing for your use of "usa"..
while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
^^^ ^
In order to do multiplication you need to use the *, ie
while(mex * (Math.pow(1.07, t)) <= usa * (Math.pow(1.02, t)))

Java pass array to method for calculation and return array

I came across this post " pass array to method Java " on how to pass an array to a method however when trying to adapt it to my intrest calculator Ive got going I get errors such as "the operator / is undefined for the argument types double[],double" and I am unable to get it resolved. I am also looking to return the whole array since I need to print the results later on and eventually sort them.
For example I define my arrays and how big they can be and then call on the user to input loan amount, interest, and frequency calculated. After I get the data and its all in array format I then pass the whole arrays off to calculate simple interest and want to return the results as an array, and then pass the same initial arrays to find compound interest by month, week, and day but I get the previously mentioned error when it tries to do the division involved in "A = P(1+ (r/n))^(n*t)" The gathering data works fine I just cannot seem to pass arrays correctly or loop through them once I do IF I'm passing them right
Any and all assistance is appreciated as always.
Relevent code
call data from user
do {
arrPrincipalAmt[i] = getPrincipalAmount();
arrInterestRate[i]= getInterestRate();
arrTerm[i] = getTerm();
i++;
if (i < 4)
{
/*
* if "i" comes to equal 4 it is the last number that will fit in the array of 5
* and will Skip asking the user if they want to input more
*/
System.out.println("Enter another set of Data? (Yes/No):");
boolean YN = askYesNo();
if (YN == true)
{
more = true;
}
else if (YN == false)
{
more=false;
}
}
else
{
more = false;
}
}while(more);
while (run)
{
//Start calculations call methods
final int dINy = 365; //days in year
final int mINy = 12; //months in year
final int wINy = 52; //weeks in year
double loanYears =(double) arrTerm[i]/mINy; //convert loan months into fraction of years, or whole years with decimals.
arrSimple= calculateSimpleInterest(arrPrincipalAmt, arrInterestRate,loanYears);
//Simple IntrestloanAmount * (annualInterestRate/100.0) * loanYears;
arrCompoundMonthly = calculateCompundInterest(arrPrincipalAmt, arrInterestRate,mINy,loanYears);
//rewrite month compound:loanAmount * Math.pow((1+((annualInterestRate/100)/mINy)),(loanYears*mINy)) - loanAmount;
simple interest that fails
public static double[] calculateSimpleInterest(double[] arrPrincipalAmt, double[] arrInterestRate, double Years)
{
for(int i=0; i<arrPrincipalAmt.length; i++)
{
double simpInterest= arrPrincipalAmt[i] * (arrInterestRate[i]/100.0) * Years; //Simple Interest Calculation
}
return simpInterest;
}
compound interest that fails
public static double[] calculateCompundInterest(double[] arrPrincipalAmt, double[]
arrInterestRate, double frequency, double time)
{
/*The Compound Interest calculation formation is as follows:A = P(1+ (r/n))^(n*t) - P
A = total interest amount only.
P = principal amount (loan amount or initial investment).
r = annual nominal interest rate (as a decimal not a percentage).
n = number of times the interest is compounded per year.
t = number of years (don't forget to convert number of months entered by user to years).
*/
for (int i=0; i < arrPrincipalAmt.length; i++)
{
double[] compound= arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i]; //Compound Interest monthly, weekly and daily depending on the frequency passed
}
return compound;
}
If you are getting an error like the operator / is undefined for the argument types double[],double it means that you are trying to divide the entire array by a value rather than a single element.
Change a line like myarray / value to myarray[i] / value
i checked your code and the problem is that at line 227 you define compound as a double array while the result of the expression at that line is simply a double.
I think you want to do so:
double[] compound = new double[arrPrincipalAmt.length];
for (int i=0; i < arrPrincipalAmt.length; i++) {
compound[i] = arrPrincipalAmt[i] * Math.pow((1+(arrInterestRate[i]/100.0)/frequency),(frequency*time)) - arrPrincipalAmt[i];
}
return compound;

Categories