Compound interest - java

import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.

First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.

import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}

A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.

Related

How do I do calculations in a separate method then send them back to main for printing?

I am trying to do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}

Program Stops at the Beginning of My Program

i am new to programming, and i was wondering if i could get some help. My program stops running at System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");. I am open to any suggestion. Also, please point out anything else wrong with this program. Thanks!
import java.util.Scanner;
public class Interest
{
double userInput;
double interest;
double time;
double amount;
double answer;
Scanner myScanner = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
}
{
System.out.println("Please enter your percent of interest in a decimal format: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
interest = userInput;
}
else
{
System.out.println("Please enter a integer for your percent of interest.");
}
}
{
System.out.println("Please enter the time the interest is applied for: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
time = userInput;
}
else
{
System.out.println("Please enter an integer for the time the interest is applied for.");
}
}
{
System.out.println("Please enter your amount of money that the interest is applied to: ");
userInput = myScanner.nextDouble();
if(myScanner.hasNextDouble())
{
amount = userInput;
}
else
{
System.out.println("Please enter an integer for the amount of money that the interest is applied to.");
}
}
{
answer = (amount * interest * time);
}
{
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
}
}
Get rid of all the extra braces; they're outside your main method.
public static void main(String[] args)
{
System.out.println("To calculate interest, we need three values. the first is the percent of interest. The second is the time the interest has to be applied for. The third is the amount of money the interest is being applied on.");
// } <-- remove
// { <-- remove
System.out.println("Please enter your percent of interest in a decimal format: ");
// -----SKIP-----
// } <-- remove
// { <-- remove
System.out.println("Your interest is $" + answer + ".");
System.out.println("Your total payment is $" + (answer + amount) + ".");
} // leave this here (end of method)
you are writing instance blocks and in main method,you did not make object creation.instance blocks are executed when you create object of class.if you want to execute those instance block you should write YourClass myclass = new YourClass()in your main method and when you run main function,those blocks outside of main()will be executed OR you should write these blocks in main method just like #shmosel's example.

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.

Java Tip Calculator for newbie

I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;

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