Im trying to make a program that calculates the compound interest of an account with the principle,interest rate, and years. Im trying to do it with dialogs/ The program has the output the return on the invesment if the principle is left to accumulate.
Im stuck on the calculation part, please help
package firstAssignment;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class thinkingQuestion {
public static void main(String[] args) {
//Banking program that asks user for the amount of money they wish to invest in a
//compound interest account (principle), the interest rate (percent value) and the time frame (years).
Scanner in= new Scanner(System.in);
String principle, interestVal, years;
int newPrinciple,newYears;
double total;
principle=JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal=JOptionPane.showInputDialog("What's the interest rate?");
years=JOptionPane.showInputDialog("How many years?");
//convert from String to integer
newPrinciple=Integer.parseInt(principle);
newYears=Integer.parseInt(years);
double newInterestVal=Integer.parseInt(interestVal);
total=JOptionPane.PLAIN_MESSAGE(newPrinciple*Math.pow(1+ newInterestVal, newYears), newYears);
I deleted somo variables you don't need, I think the main problem is on java syntax for show messages. Here you could see a tutorial:
https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
import javax.swing.JOptionPane;
public class InterestBanking {
public static void main(String[] args) {
// Banking program that asks user for the amount of money they wish to
// invest in a
// compound interest account (principle), the interest rate (percent
// value) and the time frame (years).
String principle, interestVal, years;
float newPrinciple, newYears;
principle = JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal = JOptionPane.showInputDialog("What's the interest rate?");
years = JOptionPane.showInputDialog("How many years?");
// convert from String to integer
newPrinciple = Float.parseFloat(principle);
newYears = Float.parseFloat(years);
double newInterestVal = Float.parseFloat(interestVal);
//You could change your calculation here if this isn't the need formula
double interest = newPrinciple * Math.pow(1 + newInterestVal, newYears);
//you were assigning the result to a total variable. That's not neccesary
JOptionPane.showMessageDialog(null, "Interest:" + NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(interest) + " In years: " + newYears);
}
}
Related
I'm writing a code that allows the user to dictate what type of investment they want (Annual, Monthly or Quarterly) and each investment type correlates to a specific integer: i.e. Annual = 1, Monthly = 12, and Quarterly = 4. However when I assigned annual a value, I also need it to correlate to an int value in my investment equation below and am completely stumped on how to do so.
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterest {
public static void main (String [] args)
{
Scanner cool = new Scanner (System.in);
double saving, rate;
int principal, years;
int choice;
System.out.println("Please enter you principal investment:");
/*Print statment prompts user to enter their principal investment*/
principal = cool.nextInt();
System.out.println("Would you like to have a regular investment plan?");
/* Print out statement asks user if they would like to participate in a regular investment plan*/
String question =cool.next();
System.out.println("What type of investment plan would you prefer (Annual, Quarterly, or Monthly)?");
String quest =cool.next();
while (quest.equalsIgnoreCase(("Annual")))
{ String Annual="1";
Annual.equals(choice);
}
System.out.println("Please enter the number of years that you wish to invest for:");
/* Print statement prompts user to enter the number of years that they wish to invest for*/
years = cool.nextInt();
System.out.println("Please enter the return rate per year:");
/* Print statement prompts user to enter the return rate per year*/
rate = cool.nextDouble();
saving = principal*(1+(rate/choice))* Math.pow(choice, years);
System.out.printf("%.2f", saving);
}
Once the type of investment plan is answered, you need to check if the quest variable matches any of the string you are expecting, i.e., Annual, Quarterly, or Monthly.
If the quest matches any of the choices, you assign a correct value to the choice variable, i.e., 1, 4, or 12.
You also may also need to think of situations if the answer doesn't match any of the correct choices.
if ("Annual".equalsIgnoreCase(quest)) {
choice = 1;
} else if ("Quarterly".equalsIgnoreCase(quest)) {
choice = 4;
} else if ("Monthly".equalsIgnoreCase(quest)) {
choice = 12;
} else {
//you need to do something here.
}
I would recommend using an enum that defines the int you want. I'll call the enum Plan and the int term:
public enum Plan {
ANNUAL(1),
QUARTERLY(4),
MONTHLY(12);
int term;
Plan(int term) {
this.term = term;
}
};
You would use this in your code like this (this replaces int choice):
Plan plan = Plan.valueOf(quest.toUpperCase());
saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
I think you are going to need different versions of your calculation. The enum approach would support this easily if you added a method to the enum that switches on the value of the enum. You can work out the different implementations of the calculation and define them in the case statements.
double calculateSavings(int principal, double rate, int years) {
switch (this) {
case ANNUAL:
case QUARTERLY:
case MONTHLY:
default:
return principal * (1 + (rate / term)) * Math.pow(term, years);
}
}
If you go this route you would use it in your code like this:
// saving = principal * (1 + (rate / plan.term)) * Math.pow(plan.term, years);
saving = plan.calculateSavings(principal, rate,years);
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
I am brand new to Java, started two weeks ago and am having issues wrapping my mind around this issue. I have a problem in a class I am taking that has been brought up before. Converting kilograms to pounds and rounding to the second decimal place.
I can create the input side of things and bring up a dialog box to prompt the user to enter in a weight. I can also create an output that uses an equation I made to output the answer in a dialog box.
My question is how do I take the information that is input and use it to convert from kilograms to pounds?
I have been reading my book and scouring the internet trying to find an answer and I think I may be over thinking it. Thanks for the help.
Input.java:
//This program asks a user to input a weight in kilograms.
package module2;
import javax.swing.*;
public class Input {
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
}
}
Output.java:
//This program outputs a converted weight from kilograms to pounds.
package module2;
import javax.swing.JOptionPane;
public class Output {
public static void main(String[] args) {
double kg = 75.5;
double lb = 2.2;
double sum;
sum = (kg * lb);
JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
}
}
Right now you have 2 main methods. Both of these are entry points for the program. Since they have to share information, it doesn't make sense you have both.
What I'd recommend is to change the Output's main method to a instance method, taking one parameter: the weight from the Input.
Like so:
public void printOutput(final double weight){
//...
}
You can then call that from the Input's main method like so:
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number
Output output = new Output(); // Create a new instance of the Output class
output.printOutput(kg); // Call our method to display the output of the conversion
}
One other thing, is that since Output is currently only used for that one method, you could consider just moving that method into Input.
// addition of two integers using JOptionPane
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
I am learning Java and am working on a basic program where a user can input a cost figure, an inflation percentage and a time (years) in order to calculate a cost including inflation.
I am using three classes, 1 application class, 1 driver class and 1 singular class. I am doing this as per the book to build OOP skills (I know there are simpler procedural / structured methods but that is not the point of my exercise).
The issue I am having that the output answer is $0 regardless of the figures I enter. This should not be the case obviously. If someone could please skim over my code and point me in the right direction I would be grateful.
Application Class:
package priceestimator;
public class PriceEstimator {
public static void main(String[] args) {
CostCalculator CostCalc = new CostCalculator();
CostCalc.calculateCost();
}
}
Driver Class:
public class CostCalculator {
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
}
}
Singular Class:
package priceestimator;
import java.util.Scanner;
public class Calculator {
private Scanner myScanner = new Scanner(System.in);
private double cost;
private double time;
private double costDif;
private void setTime(int time){
this.time = time;
}
private double getTime(){
return time;
}
private void setCost(double cost){
this.cost = cost;
}
private double getCost(){
return cost;
}
private void setCostDif(double costDif){
this.costDif = costDif;
}
private double getCostDif(){
return costDif;
}
private void getMyScanner(){
this.myScanner = myScanner;
}
public void calculator(){
System.out.println("Enter the current cost (numbers only):");
cost = myScanner.nextDouble();
}
public void years(){
System.out.println("Enter the time difference in years:");
time = myScanner.nextDouble();
}
public void inflation(){
double costTimeDif;
double decimalConversion;
int percent = 100;
double input;
System.out.println("Enter the current inflation rate percentage (numbers only):");
input = myScanner.nextDouble();
decimalConversion = input / percent;
costTimeDif = time * decimalConversion;
costDif = cost * costTimeDif;
}
public void price(){
double price;
price = costDif + cost;
System.out.println("The estimated price is: $" + price);
}
}
Thanks for your time.
You're using different instances of Calculator in the calculateCost(). Use the same instance to get all the details and to calculate the final price as well.
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
}
As you're using different instances, each instance has its own copy of the instance variables(which you're ultimately using to calculate the final price) and that's why for each instance only that particular value is being populated. Using the same instance would populate all the values by calling the various methods and thus, the price would be calculated using all the values entered by you via the different methods.
You have:
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
You are creating a different Calculator for every piece of information you input. Each of those is independent of the others. Instead, you mean:
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
Each Calculator has its own copy of the instance fields (and they're initialized to 0 be default). Setting e.g. the time difference in one does not affect the time difference set in the others.
The objects you instantiate should reflect, conceptually, what you are trying to do. Was your intention to have 4 separate calculators? Or was your intention to have a single calculator with all of the information? Of course, it was the latter -- and your code should reflect that.
I am doing an assignment for class and we just started making our own methods and what I thought seemed easy enough has become extremely frustration and hoping you can help me wrap my head around it.
First things first and the assignment I am trying to complete is this: make a modular program to calculate monthly payments, seems easy but the few restrictions on this question is as follows
The main method should:
Ask the user for
the loan amount
the annual interest rate ( as a decimal, 7.5% is 0.075 )
the number of months
And
call a method to calculate and return the monthly interest rate (annual rate/12)
call a method to calculate and return the monthly payment
call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment.
I have gotten to the end of just printing out the loan statement but cant for the life of me the proper way to call it, and make it show up once I run the program :/ so if you can help me understand how its done I would greatly appreciate it.
(I realize that there are probably other mistakes in my code but for right now I would rather just focus on what I need to get done)
import java.util.Scanner;
public class LoanPayment {
/**
* The main method declares the variables in program while getting the user
* info of amount loaned, interest rate of the loan, and the loans duration.
*
* The main method also calls other methods to calculate monthly interest
* monthly payments and the output of the loan statement
*/
public static void main(String[] args)
{
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
} // end main ()
/******************************************************************************/
// this class calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
/******************************************************************************/
// this class calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
/******************************************************************************/
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
If // call method to print loan statement is all you have left to do, then this is what you need on the line below it:
loanStatement(principle, interest, time, mPayment);
And it should work fine.
Your other methods have non-void return types, so you put someVariable = yourMethod(yourArguments) in order to accept the return value. However, loanStatement has a void return type. You don't need to do this. You can call it simply as I showed above and it will execute the code in the method.
Though, my personal preference would be to change loanStatement to a String return type and put the print statement in main and print the return of loanStatement. Methods that return Strings almost as easily and are more flexible for future use (for example, if you wanted to allow your program to also write to file, you need two loanStatement methods, or to completely rework loanStatement).
Check out this solution ;)
public class LoanStatement{
public static void main(String []args){
// declare variables
double interest; // interest attributed to the loan
double mInterest; // loans interest divided by 12
int time; // how long the loan was taken out for
double principle; // the amount borrowed
double mPayment; // how much is to be paid each month
double loan;
// initate new scanner class
Scanner keyboard = new Scanner(System.in);
// get user input/information
System.out.println("Hi, Please enter the loan amount here:");
principle = keyboard.nextDouble();
System.out.println("Thanks, now what is the annual interest rate in decimal notation" +
"(example: 7.5% is 0.075:");
interest = keyboard.nextDouble();
System.out.println("now please put in the number of months the loan was taken out for");
time = keyboard.nextInt();
// call method to calculate and return monthly interest rate
mInterest = calcMInterest( interest );
// call method to calculate and return the monthly payment
mPayment = calcMPayment (mInterest, principle, time);
// call method to print loan statement
loanStatement(principle,interest,time,mPayment);
}
// this method calculates and returns the monthly interest on the loan
public static double calcMInterest( double interest )
{
double mInterest;
mInterest = (interest / 12);
return mInterest;
} // end calcMInterest
// this method calculates and returns the monthly payment
public static double calcMPayment (double mInterest, double principle, int time)
{
double mPayment;
mPayment = (mInterest * principle) / (1-(1+ Math.pow(mInterest,-time)));
return mPayment;
} // end calcMPayment
// this class prints a loan statement showing the amount borrowed
// and the amount borrowed, the annual interest rate, the number of months
// and the monthly payment
public static void loanStatement(double principle, double interest, int time, double mPayment)
{
System.out.println(" principle is" + principle);
}
}