compound interest after 1, 3 and 5 years - java

i have this code that calculates the compound interest, but i need it to do it for after 1, 3, and 5 years. ive tried and cant seem to get it to work. can anyone help me?
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double principal = 0;
double rate = 0;
double time = 0;
double x = 0;
System.out.print("Enter the amount invested : ");
principal = input.nextDouble();
System.out.print("Enter the Rate of interest : ");
rate = input.nextDouble();
System.out.print("Enter the Time of loan : ");
time = input.nextDouble();
x = principal * Math.pow((1 + rate/12),time);
x = Math.pow(5,3);
System.out.println("");
System.out.println("The Compound Interest after 1 year is : "
+ x);
}
}

Why do you set x to principal *((1+r/12),time), then set x=math.pow(5,3)?
x is now set to math.pow(5,3) and has nothing to do with your inputs of principal, rate, and time.
Also, you should specify that the time input is years, as you have that hard coded in the rate question.

Related

How to add months and days for a simple interest-rate calculation (Java)

I am working on a program for an assignment.
There I got stuck on how to add the days and months for my program.
I can already convert the simple interest into years, but not for months and days:
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
double PAmount, ROI, TimePeriod, simpleInterset;
Scanner scanner = new Scanner(System.in);
System.out.print(" Please Enter the Principal Amount : ");
PAmount = scanner.nextDouble();
System.out.print(" Please Enter the Rate Of Interest : ");
ROI = scanner.nextDouble();
System.out.print(" Please Enter the Time Period in Years : ");
TimePeriod = scanner.nextDouble();
simpleInterset = (PAmount * ROI * TimePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + PAmount + " is = " +
simpleInterset);
}
}
Just ask them separatly then compute the global time
System.out.print(" Please Enter the Principal Amount : ");
double pAmount = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Rate Of Interest : ");
double rOI = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Time Period in Years : ");
double years = Double.parseDouble(scanner.nextLine());
System.out.print("And months : ");
double months = Double.parseDouble(scanner.nextLine());
System.out.print("And days");
double days = Double.parseDouble(scanner.nextLine());
double timePeriod = years * months / 12 + days / 365;
double simpleInterset = (pAmount * rOI * timePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + pAmount + " is = " + simpleInterset);
I'd suggest :
don't define variable before using it if you don't need to do so
use nextLine and parse what you need, you'll avoid suprise with return char
as Java convention, use lowerCamelCase to name your variables

Code produces no output java

Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!

How would you write Junit tests for this code?

Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.

Proper Formatting

I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Categories

Resources