calculating interest on a certificate of deposit - java

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++;
}

Related

Trouble with Choice Menu and user generated input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to make a program that takes user generated monthly rainfall numbers and and averages them, finds the max and min, finds standard deviation etc. I seem to have most everything down but my "find numbers above and below the average" doesn't seem to be working. Also i cant figure out how to let the user make another choice once they have selected and then been given the desired info. Any help would be greatly appreciated.
example output
import java.util.Arrays;
import java.util.Scanner;
public class RainfallAnalyzer {
public static void main(String[] args) {
double theRainfall = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
double[] rainfall = new double[12];
System.out.println("Enter the rainfall measurements for this year: ");
for (int i = 0; i < rainfall.length; i++) {
theRainfall = scan.nextDouble();
rainfall[i] = theRainfall;
total += rainfall[i];
}
int choiceentry = -1;
loop:
while (choiceentry !8) {
System.out.println("1. print all rainfall measurements");
System.out.println("2. print the avererage rainfall");
System.out.println("3. print the maximum and minimum rainfall measurements");
System.out.println("4. print the number of months above average rainfall");
System.out.println("5. print the number of months below average rainfall");
System.out.println("6. print the median rainfall measurement");
System.out.println("7. print the standard deviation");
System.out.println("8. exit");
if (scan.hasNextInt()) {
choiceentry = scan.nextInt();
}
switch (choiceentry) {
case 1:
for (int i = 0; i < rainfall.length; i++) {
System.out.println("Month # " + (i + 1) + ": " + rainfall[i]);
}
break loop;
case 2:
total = total / 12;
System.out.println("This year's average rainfall: " + total);
break loop;
case 3:
Arrays.sort(rainfall);
System.out.println("Min value " + rainfall[0]);
System.out.println("Max value " + rainfall[rainfall.length - 1]);
break loop;
case 4:
int numRainfallAbove = 0;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] >= avg) {
numRainfallAbove++;
} else {
}
}
System.out.println("Number of months above the average rainfall: " + numRainfallAbove);
break loop;
case 5:
int numRainfallBelow = 0;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] <= total) {
numRainfallBelow++;
} else {
}
}
System.out.println("Number of months below the average rainfall: " + numRainfallBelow);
break loop;
case 6:
double median;
if (rainfall.length % 2 == 0) {
median = ((double) rainfall[rainfall.length / 2] + (double) rainfall[rainfall.length / 2 - 1]) / 2;
} else {
median = (double) rainfall[rainfall.length / 2];
}
System.out.println("This year's median rainfall: " + median);
break loop;
case 7:
double theDeviation = deviation(rainfall, total);
System.out.println("The standard deviation is " + theDeviation);
break loop;
}
}
}
public static double deviation(double[] rainfall, double total) {
double endResult = 0;
double temporary = 0;
double arraySum = 0;
double average = total;
double sum = 0;
for (int i = 0; i < rainfall.length; i++) {
sum += Math.pow((rainfall[i] - average), 2);
}
temporary = sum / (rainfall.length - 1);
endResult = Math.sqrt(temporary);
return endResult;
}
}
Change the code within your case 4:
int numRainfallAbove = 0;
for(int i = 0; i < rainfall.length; i++){
if(rainfall[i] >= total){
numRainfallAbove++;
} else{}
}
System.out.println("Number of months above the average rainfall: "+numRainfallAbove);
break loop;
To this:
int numRainfallAbove = 0;
double avg = total / 12;
for (int i = 0; i < rainfall.length; i++) {
if (rainfall[i] >= avg) {
numRainfallAbove++;
}
}
System.out.println("Number of months above the average rainfall: " + numRainfallAbove);
break loop;
The issue is that you compare the monthly rainfall to the total instead of the average. You will need to do something similar for your "number of months with below average rainfall".
To make it keep asking for more choices as long as the user doesn't exit, change the while loop to:
while (choiceentry != 8) {
As an aside that does not directly relate to your question, try to indent your code properly when you post, and DO NOT use goto statements or breaks which direct to labels.
Also i cant figure out how to let the user make another choice once they have selected and then been given the desired info.
Well the way you have written the code, is says (in effect)
loop: while not a valid choice:
get a choice
if it is valid choice":
act on it
break out of loop
(Note the "belt and braces" way you are terminating the loop is ... unnecessary. It is clearest to put the termination condition in the while condition only.)
So what you actually need is a way for the user to say "I want to stop now". So you could make that another choice, or you could say that an invalid choice is required.
Then you need to change the loop to say
while a valid choice:
or
while not the stop choice (or condition):
One point, have you considered what happens if you the user enters "STOP" or something else that isn't a number? Try it. Then try to explain what is actually happening.

Return to start of loop java

This is a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
I may have over-indulged myself here as I'm pretty new to programming, but I'm in too deep and want to figure this out.
With my current code the first line outputs correctly, displaying the rate, total and monthly. However, after that the code just continues to output the inner most loop. I need to return to the start of the loop. It would greatly be appreciated if you could point me in the right direction.
P.S. I am aware that my padding isn't in place. My biggest concern is getting the algorithm down on "paper" first, and then worrying about the beauty of it.
package loancalc194;
import java.util.Scanner;
public class LoanCalc194 {
public static void main(String[] args) {
//LOAN CALCULATOR
//user enters loan AMOUNT, loan PERIOD(years),
//output displays MONTHLY and TOTAL payments
//^displayed per 1/8 increment from 5-8% interest
Scanner in = new Scanner(System.in);
//prompt user
//retrieve loan amount and period
System.out.print("Please enter the loan amount: ");
double amount = in.nextDouble();
System.out.print("Please enter the loan period (years): ");
int period = in.nextInt();
//INTEREST LOOP///////////////////////////////////////////////////
double interest = .05000;
double inc = 0.00125;
interest = interest + inc;
double monthly = 0;
double total = 0;
System.out.println("Interest Rate\t\t\tTotal Payment\tMonthly Payment");
while (interest < .08){
//interest = interest + inc;
System.out.print(interest + "\t");
while (true){
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
while (true) {
monthly = ((total / period) / 12);
System.out.println(monthly);
//interest = interest + inc;
}
}
}
One loop should be enough for what you want.
Your two while(true) loops do nothing else than looping on the same values forever.
In the following code, the interest gets incremented and the new calculations computed at each loop until interest reaches your max value, this is probably what you need.
double interest = .05000;
double inc = 0.00125;
double monthly = 0;
double total = 0;
while (interest < .08){
System.out.print(interest + "\t");
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
monthly = ((total / period) / 12);
System.out.println(monthly);
interest = interest + inc;
}

Trouble using for loop in my program

In my code I am having the user type in 3 things, and for the third input I ask for the number of years. However in my for loop I can't use the variable that I ask the user to input. For example if the user were to input "3", my code would do 15 years (which is the max).
double yearInvest;
double interRate;
double numOfYears = 3;
double amountBeforeTotal;
double amountTotal;
double years;
System.out.println("Compound Interest \n");
System.out.println("This program will print out a title table that will "
+ " display the amount of a yearly investment over a period of "
+ " up to 15 years. \n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the yearly investment:");
yearInvest = input.nextDouble();
System.out.println("Enter the interest rate (%):");
interRate = input.nextDouble();
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; 15 >= years; years++) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account",
"Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
}
P.S. I am still working on the code and it is not fully done. And I would also like some advice if possible.
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; 15 >= years; years++)
Your code is getting a user inputted numOfyears which for example would be 3, for your case. Your loop is from (1..15) no matter what, since your loop's 2nd parameter is: 15 >= years.
What you are looking for is (1..numOfYears)
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();
for (years = 1; years <= numOfYears; years++)
//...more code
There are a few things that I notice about your code that might not be exactly what you want.
Firstly you are storing all of your variables as doubles which are mainly used for storing floating point (i.e. numbers with a decimal place). In place of double it might be better to use int.
Next your for loop is always going to loop 15 times with years 1 to 15. If you want this to be only numOfYears times you should have a loop that compares to numOfYears
for (years = 1; years <= numOfYears; years++) {
//TODO
}
Lastly something that is quite important for coding and something that it is easy to ignore if teaching yourself is style.
for (years = 1; 15>=years; years++ ) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account", "Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
}
This indentation gives a much clearer view of what is in your for loop and helps debugging and readablilty
You can try this if you want to print only 15 years interest rates.
for (years = 1; numOfYears >= years; years++) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account",
"Interest", "Total");
amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
if(years == 15) {
break;
}
}
This will print the interest of 15 years if user enters any number greater than 15 or else will print interest rates of all years if user enters number < 15.

Check if integers within an array are within the range

Basically, the program I am supposed to write is to get the energy usage from the customer for 12 months and then output the total usage, price for two tariffs (the formulas are included in the code) and say which tariff is cheaper. But it also has to check whether the input for each of those 12 months is within the range (greater than "0" AND less or equal to "1000").
I have found a fairly easy(?) way to do it using arrays, however I have no idea how to check whether each one of the integers scanned to be in that array are actually within the range 0 < int <= 1000
If the integer is less than 0 or greater than 1000, the program has to output a line "Please enter a valid amount" and ask for the same integer again, so that it doesn't store the wrong value, if it makes sense?
import java.util.Scanner;
public class EnergyConsumptionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total_usage;
float t1_cost, t2_cost;
final int MAX_USAGE = 1000, MIN_USAGE = 0;
int[] energyCons = new int[12];
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
energyCons[month] = scan.nextInt();
}
int totalCons = 0;
for (int month = 0; month < energyCons.length; month++) {
totalCons += energyCons[month];
}
System.out.println();
System.out.println("Total usage for the year was " + totalCons + " kWh");
t1_cost = (float) (totalCons * 0.1);
t2_cost = (float) ((totalCons * 0.09) + 50);
System.out.println("Using tariff one, the cost is: " + t1_cost);
System.out.println("Using tariff two, the cost is: " + t2_cost);
System.out.println();
if (t1_cost > t2_cost) {
System.out.println("Tariff two would be cheaper for this customer.");
} else {
System.out.println("Tariff one would be cheaper for this customer.");
}
}
}
Change your input reading loop to something like this:
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
int inputValue = scan.nextInt();
while (inputValue < 0 || inputValue > 1000) {
System.out.println("Please enter a valid amount: ");
inputValue = scan.nextInt();
}
energyCons[month] = inputValue;
}

Java - Assigning User Input to Variable / Change Counter

I'm quite new to java, although I have a fairly basic knowledge of C++.
For my assignment I am counting change and sorting it into American currency (i.e., if you had 105 cents, it would divide it into one dollar and one dime).
Logically I understand how to do this, but I'm having some serious trouble understanding the java syntax. I'm having serious trouble to find a way to assign a user-inputted value to a variable of my creation. In C++ you would simply use cin, but Java seems to be a lot more complicated in this regard.
Here is my code so far:
package coinCounter;
import KeyboardPackage.Keyboard;
import java.util.Scanner;
public class helloworld
{
public static void main(String[] args)
{
Scanner input new Scanner(System.in);
//entire value of money, to be split into dollars, quarters, etc.
int money = input.nextInt();
int dollars = 0, quarters = 0, dimes = 0, nickels = 0;
//asks for the amount of money
System.out.println("Enter the amount of money in cents.");
//checking for dollars, and leaving the change
if(money >= 100)
{
dollars = money / 100;
money = money % 100;
}
//taking the remainder, and sorting it into dimes, nickels, and pennies
else if(money > 0)
{
quarters = money / 25;
money = money % 25;
dimes = money / 10;
money = money % 10;
nickels = money / 5;
money = money % 5;
}
//result
System.out.println("Dollars: " + dollars + ", Quarters: " + quarters + ", Dimes: " + dimes + ", Nickels: " + nickels + ", Pennies: " + money);
}
}
I would really appreciate some help with how to assign a user-input to my variable, Money. However, if you see another error in the code, feel free to point it out.
I know this is really basic stuff, so I appreciate all of your cooperation.
Change this line :
Scanner input new Scanner(System.in);
To :
Scanner input = new Scanner(System.in);
And this should be after line below not before:
System.out.println("Enter the amount of money in cents.");
And as you did , the line below will read from input int value and assign it to your variable money :
int money = input.nextInt();

Categories