I have been working on a program that is a Java loan payment calculator for my comp sci class. The programs requriements are:
ask user for loan amount, annual interest rate, and number of months
call a method to calculate and return the monthly interest rate
call a method to calculate and return the monthly payments
call a method to print a loan statement showing the amount borrowed, annual interest rate, the number of months and the monthly payment.
This is my first time working with multiple methods. I have developed the code so far as shown below. The netbeans editor is not giving me any errors, however, it does not print the statements from my last method. My questions are:
are my methods set up correctly and passing parameters correctly
why won't the statements print at the end
am i capturing my other methods correctly? Do i need to enter variables in the main method and then call them in the final method.
is any of my code redundant?
I am not really sure how to proceed from here.
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
}
*************************************************
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
**************************************************************************************
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
****************************************************************************************
public static void loanStatment (double loanAmount, double annualInterestRate, intnumberOfMonths, double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end main method
}//end main method
Have a look at your main method and you will see that all you are doing is declaring your variables and receiving input. Your other methods that perform the calculations and the loanStatment (sic) method that prints your results are never called.
I would recommend you read up on the basics as you will waste less of your time with very simple errors like this one.
You need to change your main method like shown below.
import java.util.Scanner;
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
System.out.println("Please enter your monthly payment.");
monthlyPayment = keyboard.nextDouble();
System.out.println("Your monthly interest rate is ");
System.out.println(calcMonthlyInterestRate(annualInterestRate));
System.out.println("Your monthly payment is ");
System.out.println(calcMonthlyPayment(calcMonthlyInterestRate(annualInterestRate),loanAmount,numberOfMonths));
loanStatment(loanAmount,annualInterestRate,numberOfMonths,monthlyPayment);
}
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
public static void loanStatment (double loanAmount,
double annualInterestRate,
int numberOfMonths,
double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end of CarLoan
I would really suggest you read up a little on how main method works in Java.That will be helpful.
Related
I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);
I have a question for yall, I am using loops for the following program and I cant understand how to make it so it displays each payment per month,
You are going to write a program which will display the payment schedule for a loan given an interest rate and the number of payments.
Prompt the user for a loan amount, the annual interest rate, number of years to pay off the loan. First, you will calculate the monthly payment using a formula below. Then you will write a loop displaying the monthly payment breakdown: interest amount, principal applied to the loan, and the balance of the loan.
For a 1 year loan (12 monthly payments) for $10,000 at 7%, the payment breakdown looks like the following:
monthly payment = 865.27
payment:1 interest: 58.33 principal: 806.93 balance: 9193.07
HERE IS THE ISSUE ABOVE I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT.
import java.text.NumberFormat;
import java.util.Scanner;
public class MothlyPay {
public static double calculateMonthlyPayment(
int loanAmount, int termInYears, double interestRate) {
// Convert interest rate into a decimal
// eg. 6.5% = 0.065
interestRate /= 100.0;
// Monthly interest rate
// is the yearly rate divided by 12
double monthlyRate = interestRate / 12.0;
// The length of the term in months
// is the number of years times 12
int termInMonths = termInYears * 12;
// Calculate the monthly payment
// Typically this formula is provided so
// we won't go into the details
// The Math.pow() method is used calculate values raised to a power
double monthlyPayment =
(loanAmount*monthlyRate) /
(1-Math.pow(1+monthlyRate, -termInMonths));
return monthlyPayment;
}
public static void main(String[] args) {
// Scanner is a great class for getting
// console input from the user
Scanner scanner = new Scanner(System.in);
// Prompt user for details of loan
System.out.print("Enter loan amount: ");
int loanAmount = scanner.nextInt();
System.out.print("Enter loan term (in years): ");
int termInYears = scanner.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = scanner.nextDouble();
// Display details of loan
double monthlyPayment = calculateMonthlyPayment(loanAmount, termInYears, interestRate);
double totalPayed = 0;
int month = 1;
double loanAmountRemaining;
// NumberFormat is useful for formatting numbers
// In our case we'll use it for
// formatting currency and percentage values
while(totalPayed <= loanAmount){
totalPayed = totalPayed + monthlyPayment;
double totalLoanAmount = loanAmount + interestRate;
loanAmountRemaining = totalLoanAmount - totalPayed;
month ++;
}
if(monthlyPayment > loanAmount)
totalPayed = totalPayed + loanAmountRemaining;
}
// Display details of the loan
//HERE IS THE ISSUE BELOW, I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT FOR THE FOLLOWING VARIABLE LISTED IN THE PRINTF STATEMENT.
System.out.printf("%9s %9s %9s %9s\n", "monthlypayment", "interestRate", "loanAmount", "loanAmountRemaining");
}
//When user put in the loan amount, interest rate, months, It needs display like the picture below.
Right now, you don't have your print statement in any specific method, meaning it won't be called. I would recommend putting it in your main method, and then running a loop to find and print your values.
Java Gurus,
Working on a class assignment and we are given a set of two programs. One calls on another to calculate interest rate, balances, etc for a bank account. What I am having problems with, is figuring out where I am supposed to input the variables we are given to get a successful compile for our program. Below are the two Java files we were given. I made the adjustments to correct all the purposeful errors in the code so everything compiles nicely so far.
public class BankAccount {
private double balance; // Account balance
private double interestRate; // Interest rate
private double interest; // Interest earned
/**
* The constructor initializes the balance
* and interestRate fields with the values
* passed to startBalance and intRate. The
* interest field is assigned to 0.0.
*/
public BankAccount(double startBalance, double intRate) {
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
/**
* The deposit method adds the parameter
* amount to the balance field.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* The withdraw method subtracts the
* parameter amount from the balance
* field.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
* The addInterest method adds the interest
* for the month to the balance field.
*/
public void addInterest() {
interest = balance * interestRate;
balance += interest;
}
/**
* The getBalance method returns the
* value in the balance field.
*/
public double getBalance() {
return balance;
}
/**
* The getInterest method returns the
* value in the interest field.
*/
public double getInterest() {
return interest;
}
}
Here is the Program2.java which is what we need to compile:
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay " + "into your account.");
account.deposit(pay);
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
// Withdraw some cash from the account.
System.out.print("How much would you like " + "to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned %bodyquot; + formatter.format( account.getInterest() )" +
" in interest.");
System.out.println("Now your balance is %bodyquot; + formatter.format( account.getBalance() ) )");
}
}
What I am required to enter is 500 for Starting Balance, 0.00125 for Monthly Interest Rate (Interest is compounded monthly in the code and pretty sure I know where to put this variable), 1000 Monthly Pay and 900 withdrawl amount. The end result should be $600.75.
Is all of my code there or do I need to declare the value of the variables Starting Balance, Interest Rate, Monthly Pay and Withdrawl Amount?
Please let me know if I am doing something wrong, or if the answer is smack in front of my face and I am just blind today.
Its a copy paste issue in your code.
Change From:
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
To:
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
Use below mentioned updated code.
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
// Withdraw some cash from the account.
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned " + formatter.format( account.getInterest() ) +
" in interest.");
System.out.println("Now your balance is " + formatter.format( account.getBalance() ) );
}
}
You're going to want to input those values either when you create your BankAccount class in your second program or at runtime. You could try something like this:
BankAccount account = new BankAccount(500, 0.00125)
And then input the rest of the values at runtime, or you could create local variables in Program 2 for everything and then create a new BankAccount using them as parameters.
Hope it helps.
I'm a beginner to Java, and I'm trying to write a simple Java program that calculates an amount in a savings account based on an initial amount deposited, number of years, and an interest rate. This is my code, which compiles, but does not actually print the amount of money in the account (basically, it completely ignores my second method).
import java.util.*;
class BankAccount {
public static Scanner input = new Scanner(System.in);
public static double dollars;
public static double years;
public static double annualRate;
public static double amountInAcc;
public static void main(String[] args) {
System.out.println("Enter the number of dollars.");
dollars = input.nextDouble();
System.out.println("Enter the number of years.");
years = input.nextDouble();
System.out.println("Enter the annual interest rate.");
annualRate= input.nextDouble();
}
public static void getDouble() {
amountInAcc = (dollars * Math.pow((1 + annualRate), years));
System.out.println("The amount of money in the account is " + amountInAcc);
}
}
I think it is because I don't call the method anywhere, but I'm a bit confused as to how/where I would do that.
Call it once you have received all the required inputs from the Scanner.
// In main
System.out.println("Enter the number of dollars.");
dollars = input.nextDouble();
System.out.println("Enter the number of years.");
years = input.nextDouble();
System.out.println("Enter the annual interest rate.");
annualRate= input.nextDouble();
getDouble(); // Print out the account amount.
The main method is pretty much the entry point for the program to run. To call a static method in java you can just go:
public static void main(String[] args) {
...
BankAccount.getDouble();
...
}
If it wasn't static you have to create an instance of the class. like:
BankAccount account = new BankAccount();
account.getDouble();
The idea of this assignment is to have multiple methods interact with each other. I am asking the user for loan amount, interest rate and duration of loan. Then the program is supposed to have one method that calculates the monthly rate, one method that calculates and returns the monthly payment and a method to print the loan statement (amt borrowed,annual interest rate, number of months, and the monthly payment).
I am not receiving any errors in the editor but my program just asks for the three inputs from the user and does not print the loan statement. Any suggestions?
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
}
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
public static void loanStatment (double loanAmount, double annualInterestRate, intnumberOfMonths, double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end main method
}//end main method
I am not sure if some of my code is still redundant.
Since the main method is static and your CalcMonthlyInterestRate references your main method the CalcMonthlyInterestRate must also be static so that the two create a static reference to each other.
At the bottom of your post we see:
}//end main
}//end class
Class Methods referenced by the main method must also be inside its same class as well as being static. Once you start building your own classes and objects this won't always be the case
}//end main
public static double CalcMonthlyInterestRate(double annualInterestRate) {
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}
}//end class
To capture a double using your method just call something like this in your main method:
double answer = CalcMonthlyInterestRate(/*some double variable here*/); //in main
Your method CalcMonthlyInterestRate need to be within your CarLoan class and not outside of it.
That's because you have it like this:
import java.util.Scanner;//instance of scanner class for input from user
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
}
}//end main method
public static double CalcMonthlyInterestRate(double annualInterestRate)
{
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}
There are a couple problems here... One is that //end main method is not really the end of the main method. It's the end of your class. All methods in Java have to be inside a class. Classes represent objects, and Java is "object-oriented". Each method on an object represents a "behavior" of that object. A behavior dangling applied to nothing is (most of the time) meaningless.
The "class, interface, or enum" expected means that where you are currently typing code, you can only put a class, an interface, or an enum. Those are the top level constructs of a Java program (unless you want to get technical with packages, etc...)
Putting the function inside the class (and fixing some code redundancy), we have:
import java.util.Scanner;//instance of scanner class for input from user
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
double monthlyInterestRate = CalcMonthlyInterestRate(annualInterestRate);
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
} //end main method
public static double CalcMonthlyInterestRate(double annualInterestRate)
{
return annualInterestRate / 12;
} //end monthly interest method
} //end class
Also, methods in Java usually start with a lowercase letter.