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);
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);
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);
}
}
Hello I am a beginner and currently trying to learn java programming.
The question in the textbook:
Write a program that helps a person decide whether to buy a hybrid car. Your program’s inputs should be:
•The cost of a new car
•The estimated miles driven per year
•The estimated gas price •The efficiency in miles per gallon
•The estimated resale value after 5 years
Compute the total cost of owning the car for five years. (For simplicity, we will not take the cost of financing into account.) Obtain realistic prices for a new and used hybrid and a comparable car from the Web. Run your program twice, using today’s gas price and 15,000 miles per year. Include pseudocode and the program runs with your assignment.
My question: I got the code right, my program runs perfectly. My main concern is how can I present this in a professional manner. How can I structure it professionally, what would I have to do in order to have it published (for example). I am trying to get in the habit of having my codes organized and neatly presented. Any suggestions would help, thanks!
public class car
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Car Model: ");
String carModel = in.nextLine();
System.out.print("Cost of Car: ");
int costOfCar = in.nextInt();
System.out.print("The estimated miles driven per year: ");
int milesDriven = in.nextInt();
System.out.print("The estimated gas price: ");
int gasPrice = in.nextInt();
System.out.print("Efficiency in miles per gallon: ");
int milesPerGallon = in.nextInt();
System.out.print("Estimated resale value after 5 years: ");
int retailValue = in.nextInt();
double carEfficiency = (double) gasPrice / milesPerGallon;
double milesDrivenCost = (double) milesDriven * carEfficiency * 5; //5 years of driving
double retailValueInFiveYears = retailValue;
double carUseLoss = costOfCar - retailValueInFiveYears;
double totalCost = carUseLoss + milesDrivenCost;
System.out.print(carModel + " will cost you after 5 years: ");
System.out.format(" %,d%n", Math.round(totalCost));
}
}
I hope that's not your real indentation.
Use Java naming conventions. In particular, class car should be 'Car'.
I would have said add a few comments, but variable names are pretty descriptive.
Add JavaDoc comments to the class and to the main method.
Always close resources explicitly.
The user could want to enter several of the inputs with decimals. Use doubles instead of ints. Scanner will accept numbers with no decimals too.
Perhaps you could include the generated JavaDoc HTML output.
Java code:
import java.util.Scanner;
/**
* Computes a car's 5-year cost of ownership.
* Usage:
* java Car
*
* #author Mario Rossi
*/
public class Car {
/**
* Computes a car's 5-year cost of ownership.
*
* #param args Not used.
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Car Model: ");
String carModel = in.nextLine();
System.out.print("Cost of Car: ");
double costOfCar = in.nextDouble();
System.out.print("Estimated miles driven per year: ");
double milesDriven = in.nextDouble();
System.out.print("Estimated gas price in $ per gallon: ");
double gasPrice = in.nextDouble();
System.out.print("Efficiency in miles per gallon: ");
double milesPerGallon = in.nextDouble();
System.out.print("Estimated resale value after 5 years: ");
double retailValueInFiveYears = in.nextDouble();
in.close();
double carEfficiency = gasPrice / milesPerGallon;
double milesDrivenCost = milesDriven * carEfficiency * 5; //5 years of driving
double carUseLoss = costOfCar - retailValueInFiveYears;
double totalCost = carUseLoss + milesDrivenCost;
System.out.print(carModel + " will cost you after 5 years: ");
System.out.format(" %,.2f%n", totalCost );
}
}
First of all you need to use the Object Oriented approach i.e. follow the rules:
Abstraction : Identify the entities as classes and their attributes
and operations. you have created a class Car but not defined its
attributes and operations properly so think around it.
Enacapsulation: Data hiding, make sure you use the proper access
specifiers for your Class attributes and operations
Inheritence: Car is quite an abstract thing, so you better define an
abstract class. And inherit real classes such as Ford Car, Merc Car
from your base Car class.
Polymorphism : When you define your Car and its subclasses, you may
have to override the methods define in your abstract class into your
child classses.
Packaging the software: You can do it in multiple ways:
Package it is an executable jar, so a user can simply double click it and run
Create an exe file, which internally calls your java code.
etc
you may have to write a release note or a small documentation to mention that jre should be installed on the computer, path should be set etc.
hope it helps!
as you said you are beginner and started to learn the java, you should always keep the following things in mind,
As Java is object oriented and your program is like as c program you must use the OOPs concepts like class, object and all.
While writing the program you should use the proper indentation.
While giving names for variables, methods use proper naming conventions and don't forget to give comments so that new users can get for what purpose what things you have given.
As you learn new thing try to implement these in your programs or in project.
Try the packages and try to keep small classes and programs so that you will not get confused in the future as well as other users too.
If you find this answer is useful then don't forget to mark as accepted..
Been wracking my brain for hours trying to figure this out.
i have the main method which is:
public static void main(String [] args)
{
double payRate;
double grossPay;
double netPay;
int hours;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Pay Roll Program");
printDescription();
System.out.print("Please input the pay per hour: ");
payRate = input.nextDouble();
System.out.println("\nPlease input the pay per hour: ");
hours = input.nextInt();
System.out.println("\n");
netPay = computePaycheck(netPay);
System.out.println("The net pay is $" + (netPay));
System.out.println("We hope you enjoyed this program");
System.exit(0);
and the method that calculated the netPay
public static double computePaycheck(double payRate, int hours)
{
double grossPay = computePaycheck(payRate*hours);
double netPay = (grossPay - (grossPay *.15));
return netPay;
}
But I'm getting the error "computePaycheck(double,int) in PayCheck cannot be applied to (double)"
I sort of understand this, but I can't for the life of me figure out a remedy.
1) You are calling a function with 2 parameters while only passing 1. That will cause a compilation error.
2) When you call computePaycheck from within itself that will loop and cause a stack overflow.
netPay = computePaycheck(netPay);
public static double computePaycheck(double payRate, int hours)
"computePaycheck(double,int) in PayCheck cannot be applied to (double)"
Your method takes two parameters, a double and an int.
You can only call it with those two (you are missing the number of hours in the call).
netPay = computePaycheck(payRate, hours);
double grossPay = payRate*hours;
In your computePaycheck method, you have the following line:
double grossPay = computePaycheck(payRate*hours);
This is passing one parameter (the product of payRate and hours) to the computePaycheck function, which requires two parameters. It looks like you meant to say:
double grossPay = computePaycheck(payRate, hours);
But you will need to be careful! This will cause your program to recur infinitely! You will need to determine how to calculate the gross pay without calling this function, since if you do call it recursively within itself, there is no condition from which it will return.
Your method takes two parameters -- double payRate and int hours, but you are only specifying a double when you call computePaycheck in your main method.
It's not clear what you intend to happen, but the mismatched parameters should let you know what is wrong with your program.
The first statement of your computePaycheck method calls computePaycheck with a single parameter (a double) whereas the computePaycheck takes 2 parameters (a double and an int). That is why your code fails to compile.
If you "fix" this by using double grossPay = computePaycheck(payRate, hours); instead, this will compile BUT you will get infinite recursion! Don't you simply want to do double grossPay = payRate*hours; ?
It's clear that you set 2 parameters but from the main class you are only calling just one parameter. You should find a way to call the 2 parameters at the same time.
public class Balance {
public static void main(String[] args) {
System.out.printf("%.2f\n", balance(0.0, 0.0, 0.0));
}
/**
* #param principal
* #param rate
* #param years
* #return
*/
public static double balance(double principal, double rate, double years) {
double amount = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the initial investment amount: ");
principal = sc.nextDouble();
System.out.print("Enter the interest rate: ");
rate = sc.nextDouble();
System.out.print("Enter the number of years: ");
years = sc.nextDouble();
for (int i = 1; i < years; i++) {
amount = principal * Math.pow(1.0 + rate, years);
amount += principal;
}
return amount - principal;
}
}
My problem is with the printf line that I am using within the main method. Eclipse wants me to change the method balance from void to Object[]. When I do this I must return a value from balance. So I guess my question is, how would I return the proper value? Am I on the right track? Thank you for your time and constructive criticism. :)
EDIT - Thanks for the help everyone, much appreciated :) My math is off. I end up with 1000 more than I should have. hmmm.
So should I just take a 1000 from amount like so:
return amount - 1000;
Or this:
return amount - principal;
EDIT this is what I am going with since it is due tonight. Thanks to all for the assistance. :)
A few points:
balance() cannot be void, because you use its return value in S.out.printf(). Do you want balance to print to the screen, or do you want it to yield a number?
Your loop for (years = 0; years > 10; years++) won't run. Think about why. It might help to convert the for into a while, to visualize why.
You read in years as a double, but then use it as a counter in your loop. What type should it actually be?
Your balance() function takes three parameters, then immediately gets input and obliterates them. Do you want balance() to be provided these numbers, or do you want it to fetch them?
Otherwise, you seem to be on the right track.
The problem is that balance doesn't return anything, (it's a void function). Change it to:
public static double balance(double principal, double rate, double years) {
...
And inside that function, return the balance.
Java is telling you it wants an Object[] because printf is defined like this:
public static void printf(String format, Object ... params) {
// params is an Object[]
}
What this lets you do is pass parameters like this:
printf("some string", first, second, etc);
It lets you pass as many parameters as you want, and the function can handle them as if you passed an array.
It's exactly the same as if it was defined like this:
public static void printf(String format, Object[] params);
And you used it like this:
printf("some string", new Object[] { first, second, etc});
It's just easier to use.
EDIT:
The other option is to not print anything in main, but I would definitely advise returning the result and printing it in main. This follows the principle of making each function do as little as possible. balance should just calculate the balance. Printing it is unrelated.
Please consider a more drastic re-working of your code; as it is, your balance() function is doing all the work of your program (and your printf() line feels like an afterthought). If you break apart your code based on what the code does, I think you can do much better:
create a function that prompts the user and then reads in their input
create a function that calls the previous function three times for principal, rate, and years
create a function that computes and populates a payment schedule. Keep track of year, balance, payment, principal payment, and interest payment. (Or just the variables you're interested in -- but be aware that programs tend to grow new features, and these variables are often the second thing that users (or professors) ask to know when paying down a loan.)
create a function that prints the selected columns from your payment schedule.
create a function that orchestrates the previous functions.
When you re-write your program to use a GUI or webservice in three weeks, you'll definitely thank yourself for having written each function to do one task, and do it well. You'll also find it far easier to test smaller pieces of code that do only one task.
There is the risk of over engineering a too-generic solution -- what I'm really trying to suggest is a functional decomposition of your code into multiple smaller routines that do exactly what their name says. You might never move the program into a GUI or webservice or whatever, but you'll definitely be happier when someone reports that your amortization schedule is wrong, that you can control it via simpler programming, rather than having to re-type inputs all day long.
Yours is wrong, do this:
public static void main(String[] args) {
balance(1000.0, .05, 8.5);
}