Java loop, need suggestion for code simplification.. - java

I am just practicing Java as a beginner. So here is the question:
Suppose you save $100 each month into a savings account with the annual interest rate 5%. Thus, the monthly interest rate is 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 and the second month will be (100 + firstMonthValue) * 1.00417, and then goes on like so every month. So here is my code:
import javax.swing.JOptionPane;
public class vinalcialApplication {
public static void main(String args[]){
String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
double monthsaving = Double.parseDouble(monthlySaving);
//define monthly rate
double monthlyrate = 1.00417;
double totalrate = monthlyrate + 0.00417;
double firstMonthValue = monthsaving * (totalrate);
double secondMonthValue = (firstMonthValue + 100)*(monthlyrate);
double thridMonthValue = (secondMonthValue + 100) * (monthlyrate);
.........
System.out.print("After the sixth month, the account value is " sixthMonthValue);
}
}
I mean the code works but it is too much code to write.. I am sure I can use a loop or if statement to do this but haven't figured a way to do it yet.. can you please help?
Thank you.

If I understand correctly, this is called compound interest.
There is a mathematical formula to achieve what you wanted without looping.
Here is the formula from wikipedia
Where,
A = future value, P = principal amount (initial investment),r = annual nominal interest, rate, n = number of times the interest is compounded per year,t = number of years
Hope this helps you in solving what you wanted. I can give you sample code, but I think it is fairly easy to convert this formula to java statement. Let us know if you need any more info.
Source: http://en.wikipedia.org/wiki/Compound_interest

import javax.swing.JOptionPane;
public class vinalcialApplication {
public static void main(String args[]){
String monthlySaving = JOptionPane.showInputDialog("Enter the monthly savings");
double monthsaving = Double.parseDouble(monthlySaving);
//define monthly rate
double monthlyrate = 1.00417;
double totalrate = monthlyrate + 0.00417;
double value = monthsaving * (totalrate);
for(int i = 1; i<6;i++) {
value = (value + 100)*(monthlyrate);
}
System.out.print("After the sixth month, the account value is " value);
}

The maths is probably wrong, but the basic concept is sound.
public static void main(String[] args) {
double monthsaving = 100;
double monthlyrate = 1.00417;
double savings = 0;
// Loop for six months...
for (int index = 0; index < 6; index++) {
savings += monthsaving * monthlyrate;
System.out.println(index + ":" + savings);
}
System.out.println(savings);
}
Take a closer look at Control Flow Statements, paying attaching with while, do-while and for statements

Related

How to raise a double to a power

Cannot figure out how to raise the formula to a power. I have imported the java.lang.Math in java also. I just keep getting the Sytax error on "Math" delete this token and cannot invoke pow(double) on the primitive data type double errors
This is the formula assuming a 30 year loan
Annuity Factor = (0.003125*(1+0.003125)^360)/(((1+0.003125)^360)-1)
the 360 is 30 years time 12 months to get the monthly payment
import java.util.Scanner;
import java.lang.Math;
public class HW3Method {
public static void main(String[] args) {
// main method for user inputs
Scanner info = new Scanner(System.in);
System.out.println("Enter the starting annual rate as a percent (n.nnn)");
double startRate = info.nextDouble();
System.out.println("Enter the ending annual rate as a percent (n.nnn)");
double endRate = info.nextDouble();
System.out.println("Enter the annual intrest rate increments as a percent (n.nnn)");
double rateIncrease = info.nextDouble();
System.out.println("Enter the first term in years for calculating payments");
double firstTerm = info.nextDouble();
System.out.println("Enter the last term in years for calculating payments");
double lastTerm = info.nextDouble();
System.out.println("Enter the term increment in years");
int termIncrement = info.nextInt();
System.out.println("Enter the loan amount");
double loanAmount = info.nextDouble();
double mtp = firstTerm * 12;
}
public double calcAnnuity(double mtp ) {
double annuityFactor = (0.003125*(1+0.003125)Math.pow(mtp));
return annuityFactor;
}
}
Explanation
You are using the method Math.pow wrong. It wants two arguments, the base and the exponent. You wrote:
0.003125 * (1 + 0.003125) Math.pow(mtp)
But you need to write:
0.003125 * Math.pow(1.0 + 0.003125, mtp)
Notes
Note that 1.0 + 0.003125 can be simplified to just 1.003125, so:
0.003125 * Math.pow(1.003125, mtp)
Even better would be to store that magical number somewhere as constant, then you only need to change one variable and not many:
private static final int FACTOR = 0.003125;
And then use that constant:
FACTOR * Math.pow(1.0 + FACTOR, mtp)
Documentation
From the official documentation of Math.pow:
public static double pow​(double a, double b)
Returns the value of the first argument raised to the power of the second argument. Special cases: [...]

Adding iterations together in Java

I'm trying to add together the sum of the iterations of a for loop. This is what I have so far.
import java.util.Scanner;
public class Pennies
{
public static void main (String [] args)
{
double amount; //To hold the amount of pennies per day
double days; //To hold the days user saved.
double total;
System.out.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
days = keyboard.nextDouble();
//Display the table
System.out.print("Day \t Salary \n");
for (amount = 1; amount <= days; amount++)
{
total = amount * .01 * amount;
System.out.println(amount + "\t \t $" + total);
}
}
}
Any help would be greatly appreciated!
In order to keep on adding the salary for each day and keeping the track of total for each day (as I get it from your statement), you can change:-
total = amount * .01 * amount;
to
total += amount * .01 * amount; // total = total + (amount*0.01*amount)
which(when not printing each day information separately) can be simplified as:-
total = amount * .01 * amount * days;
I compiled your code and noticed that your numbers were off. Assuming that you want the first day's pay to be one penny, and for it to double every following day, here's what I came up with. It's hard to tell if this is exactly what you want since you didn't actually ask a question, so let me know if this is what you're looking for.
public static void main(String[] args) {
System.out
.println("I will display a table of salary if you're paid every day in pennies and it doubles every day.");
Scanner keyboard = new Scanner(System.in);
System.out.print("How many days do you wish to save for?");
double days = keyboard.nextDouble();
// Display the table
System.out.print("Day \t Salary \n");
double pay = 0.01;
double totalPay = 0.0;
for (int i = 1; i <= days; i++) {
System.out.println(i + "\t \t $" + pay);
totalPay += pay;
pay *= 2;
}
System.out.println("Total Pay \t $" + totalPay);
keyboard.close();
}
You're originally doing total = amount*0.1*amount, which won't give you what you want. You're confusing squaring amount with simply doubling it.
Edit: Also consider changing days to an int. I don't see any reason why it should be a double

How do I call a method into my main method so it can execute the program?

Obviously, I'm not looking for all the answers but some direction would be much appreciated.
So I have this program that prompts the user to enter their annual interest rate and savings amount. The program calculates the compound value for 6 months.
I'm having issues calling the new method into the main method to execute the calculations. The main method asks the users for their annual interest rate and the savings amount. It calls the new method, and if all are positive numbers it executes the program. If any are negative it comes up with an error.
I thought I called the method in the last line with calling it but obviously I am wrong. I have tried googling and am having trouble understanding this calling aspect. Any information would be appreciated. I'm new so I'm still working on this programming thing! Not sure why that last curly bracket isn't in the code. Here's the code:
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class FifthAssignment {
static double savingAmount = 0.0; // the 2 given static doubles
static double annualInterestRate = 0.0;
int sixthMonth;
public static double compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
return sixthMonth; // sixMonth is the compound value
}
{
DecimalFormat formatter = new DecimalFormat(".00");
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
sixthMonth = (int) ((savingAmount + sixthMonth) * (1 + monthlyInterestRate));
}
}
}
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00"); // bring in the
// decimal
// formatting for
// program
String SA = JOptionPane.showInputDialog("What is your savings amount? "); // Window
// pops
// up
// asking
// for
// your
// savings
// amount.
// As
// a
// string?
savingAmount = Double.parseDouble(SA); // Returns a double given to
// value in string above
String AIR = JOptionPane.showInputDialog("What is the annual interest rate? "); // Window
// pops
// up
// asking
// for
// annual
// interest
// rate.
// String
// as
// above.
annualInterestRate = Double.parseDouble(AIR); // Returns the same as
// savings amount but
// for annual interest
// rate
{
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is "
+ compoundValueMethod(savingAmount, annualInterestRate, 6));
}
}
}
Function Call should have parenthesis
Try This:
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
Your function should return the computed value, but in your case you are returning 'void', so it should be like this
public static int compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
int res = 0;
DecimalFormat formatter = new DecimalFormat(".00");
sixthMonth = 6;
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
res = (int) ((savingAmount + res ) * (1 + monthlyInterestRate));
}
}
return res;
}
Based on the current code you have written, the function is not called properly and should look like :
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
If you always want the value of 6 to be passed to your function, then instead of having it as a parameter to the function, you should be better off declaring a static final class variable like this:
private final static int SIXTH_MONTH = 6;
If you want to read the number of months, then yes your function should have that parameter, you should read that parameter just like the other 2 params you are reading and pass it along. And you should remove the line that is assigning the value of 6 to your method parameter.
sixthMonth = 6;
and instead use the value passed in to the function from the main() function

Compare loans with various interest rates java

I am new to Java and just now started with loops.
I have tried to do this exercise:
Write 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.
So far this what i have got:
import java.util.Scanner;
public class compareLoansWithInterestRates {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Loan Amount :");
int loan = input.nextInt();
System.out.print("Number of Years" );
int years = input.nextInt();
double monthPay, totalPay,interestRate;
System.out.println( "Interest Rate \t Monthly Payment \t Total Payment");
for(double rate =0.05; rate <=0.08; rate++ ){
for (int month = 1; month <= (years*12);month++){
rate +=1/8;
monthPay = loan* rate/(1-(Math.pow(1+rate,years*12)));
totalPay = monthPay*years*12;
interestRate= rate*100;
System.out.println("\t"+interestRate+" \t "+monthPay+"\t"+totalPay);
Why doesn't it work?
Just looking at your code briefly, you're incrementing rate within your 'outer for' loop using rate++ (which will increment by 1, not 0.01). You then increment rate again within the month loop by 1/8. Try removing 'rate++' from the outer loop. Not positive this will fix all your issues, but this is just a quick observation.
Where to start…
First of all: Java:
for(double rate =0.05; rate <=0.08; rate++ ){
this is good for int, not for double
rate +=1/8;
1/8 is much more then 0.125% you are looking for. It's not Java, but mathematics.
The second line should not be here at all, and for loop should be:
for(double rate =0.05; rate <=0.08; rate+=0.00125 ){
Unfortunately, your algorithm seems to be wrong too, so this change won't fix everything. But from Java point of view it will be rather ok.
I think this'll work
for (double i = 5; i <= 8; i += 0.125) {
double rate = i / 100;
monthPay = loan * (Math.pow(1 + (rate / 12), years * 12)) / 12;
totalPay = monthPay * years * 12;
interestRate = i;
System.out.println("\t" + interestRate + " \t " + monthPay + "\t" + totalPay);
}
I put together a simple loan calculator which is slightly different from yours, to show you just how much work goes into the input and output of a Java application.
Here's the input and output.
Loan Amount 60000
Number of Months 60
Yearly Interest Rate 6
Payments on a $60,000.00 loan for 60 months
Monthly Payment Total Payment
4.000% $1,104.99 $66,299.48
4.250% $1,111.77 $66,706.40
4.500% $1,118.58 $67,114.87
4.750% $1,125.41 $67,524.88
5.000% $1,132.27 $67,936.44
5.250% $1,139.16 $68,349.54
5.500% $1,146.07 $68,764.18
5.750% $1,153.01 $69,180.37
6.000% $1,159.97 $69,598.09
6.250% $1,166.96 $70,017.34
6.500% $1,173.97 $70,438.13
6.750% $1,181.01 $70,860.46
7.000% $1,188.07 $71,284.31
7.250% $1,195.16 $71,709.70
7.500% $1,202.28 $72,136.61
7.750% $1,209.42 $72,565.06
8.000% $1,216.58 $72,995.02
Here's the code that does the actual loan calculation to get the monthly amount.
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
Pretty straightforward, right.
Now, I'm going to show you all of the code that gathered the input and produced the output. It's way longer than just the calculation. Go through the code as best you can, and I'll explain it as best I can.
package com.ggl.testing;
import java.text.NumberFormat;
import java.util.Scanner;
public class InterestRateCalculator implements Runnable {
private static final NumberFormat CF = NumberFormat.getCurrencyInstance();
private static final NumberFormat NF = NumberFormat.getNumberInstance();
private double interestRate;
private int loanAmount;
private int months;
#Override
public void run() {
getInputs();
produceOutputs();
}
public void getInputs() {
Scanner input = new Scanner(System.in);
System.out.print("Loan Amount ");
loanAmount = input.nextInt();
System.out.print("Number of Months ");
months = input.nextInt();
System.out.print("Yearly Interest Rate ");
interestRate = input.nextDouble();
input.close();
}
public void produceOutputs() {
double[] interestRates = new double[17];
double interestRate = this.interestRate - 2.0D;
for (int i = 0; i < interestRates.length; i++) {
interestRates[i] = interestRate / 100D;
interestRate += 0.25D;
}
String header = displayHeader();
System.out.println(" ");
System.out.println(header);
System.out.print(leftPad(" ", 10, ' '));
System.out.print(leftPad("Monthly Payment", 15, ' '));
System.out.println(leftPad("Total Payment", 15, ' '));
for (int i = 0; i < interestRates.length; i++) {
String s = displayInterestRate(interestRates[i]) + " ";
System.out.print(leftPad(s, 10, ' '));
double monthlyPayment = calculateMonthlyPayment(interestRates[i]);
System.out.print(leftPad(CF.format(monthlyPayment), 15, ' '));
double totalPayment = monthlyPayment * months;
System.out.print(leftPad(CF.format(totalPayment), 15, ' '));
System.out.println("");
}
}
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
private String displayHeader() {
StringBuilder builder = new StringBuilder();
builder.append("Payments on a ");
builder.append(CF.format(loanAmount));
builder.append(" loan for ");
builder.append(NF.format(months));
builder.append(" months");
builder.append(System.getProperty("line.separator"));
return builder.toString();
}
private String displayInterestRate(double interestRate) {
return String.format("%.3f", interestRate * 100D) + "%";
}
private String leftPad(String s, int length, char padChar) {
if (s.length() > length) {
return s.substring(0, length);
} else if (s.length() == length) {
return s;
} else {
int padding = length - s.length();
StringBuilder builder = new StringBuilder(padding);
for (int i = 0; i < padding; i++) {
builder.append(padChar);
}
builder.append(s);
return builder.toString();
}
}
public static void main(String[] args) {
new InterestRateCalculator().run();
}
}
The first thing that I did was use the InterestRateCalculator class as a Java object. My static main method consists of one line.
new InterestRateCalculator().run();
This line does two things. It creates an instance of the InterestRateCalculator class and it executes the run method of the class.
It may seem strange now, but getting away from static methods and static fields allows you to create complex Java applications with many, many classes. You should learn this now, while you're writing simple applications.
I implemented Runnable because a Runnable class requires a run() method. It's a personal preference of mine. You could have named the run() method execute(), or some other meaningful name.
I didn't write a constructor. I used the default constructor of InterestRateCalculator();
Looking now at the run() method, I divided the problem into two parts. Reading or getting the input and producing the output. This allows me to focus on a smaller, simpler problem than the original problem. This is called divide and conquer.
Getting the input is straightforward. I copied your code and made the prompt text consistent. I added a space at the end of each prompt so the prompts and responses would look better. I know this sounds silly, but I assure you that I spent the better part of my programming career making changes to the appearance of the input and output of applications.
Getting the output to line up took a large part of the code to produce the output. Producing the output was more complicated than gathering the input. I broke the process down into many methods. A method should do one thing, and return one output, like the calculateMonthlyPayment I showed you earlier.
I used a trick that I learned in the olden times of Cobol programming to produce the output. I left padded the Strings I created with spaces. You don't have to memorize this particular trick. Other "tricks" have been gathered together and called design patterns. Don't worry about learning any patterns right now. Just know that they exist so that you can group code into higher levels.
I hope this explanation was helpful to you. I know you wanted to write the code yourself. That's why I solved a different problem than yours.
monthpay is incorrect
monthPay = loan* rate/(1-1/(Math.pow(1+rate,years*12)))

Re-assigning the value to a double in a for loop

I'm currently working on a program that will calculate a simple interest rate and monthly payment taken from a loan. Although, I am running into one pretty big problem. I am trying to make it so that my principal value(see in code) is re-assigned the value of my new balance(see in code). Here is my code right now, I will explain in better detail under it:
import java.util.Scanner;
public class Payments {
public static double principal; //principal
public static double annualrate; //annual interest rate
public static double p; //monthly payment
public static double mr; //monthly interest rate
public static double nb; //new balance after monthly payments
public static double i; //interest (monthly)
public static String spaces = " "; //spaces for making clean columns
public static int months = 12;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Principal: $");
principal = input.nextDouble();
System.out.println("Anual Interest Rate: ");
annualrate = input.nextDouble();
System.out.println("Monthly Payment: $");
p = input.nextDouble();
calculate();
}
public static void calculate() {
mr = annualrate / 12;
i = mr * p;
nb = principal + i - p;
System.out.print("Month Principal Amt. Interest Payment New Balance");
System.out.println();
System.out.println();
for(int x = 1; nb > 0; nb = principal + i - p){
System.out.println(x + spaces + p + spaces + i + "%" + spaces + "$" + p + spaces + "$" + nb);
p = (Double)null;
p = nb;
}
}
}
So as you can most likely see by the comments in the code, all of the variables are shown. Now, disregard the null and me casting it to a double because that was the last thing that I tried to do before asking you guys :) anyways, my final question is, how can I go about re-assigning the value of principal to my new balance (nb)? Also, a side question, would a while-loop be better for this kind of program?
This has already been said in the comments, but the most immediate problem that I can see is in
for(int x = 1; nb > 0; x++){
your condition, nb > 0 will never ever change in that loop.
This means 1 of 2 things
your loop won't execute
your loop won't exit (infinite loop)
judging by how you're calculating nb(new balance) I'm assuming that it's going to be above 0 most of the time, and that your loop will never stop.
As things are right now, I'm not entirely sure what you actually want to do in that for loop or whether you even want a for loop at all, as that part is unclear.
what is the for loop supposed to do?
it almost looks like you're attempting to do something like
for (int x = 1; principal > 0; x++)
{
principal += principal * monthlyInterestRate;
principal -= payment;
System.out.println("insert output here");
}
nb = p + i - p; ???? looks like you need to double check your code.. the for loop doesnot change the condition at any place.. if the value is greater than 0, you will always lead it to an infinite loop, or it will never enter the loop at all( if np<1) . so check you code for runtime errors..

Categories