(Java Beginner) - Having trouble with a program - java

Ok so I am working on a program that involves loans and gives information to the user about loans from what the user inputs.
The purpose of this program I am writing is for the user to be asked to input a loan amount and the number of years that they have to pay it off. Once the user has given this information, the program will take the loan amount and number of years and tell the user the annual interest rate, monthly payment and the total amount.
ALSO, if the user enters a loan amount of -1, the program is supposed to terminate.
Below is my code thus far:
package Loans;
import java.util.Scanner;
public class Loans {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
double monthlyInterestRate;
double annualInterestRate;
double monthlyPayment;
double total;
double numberOfYears;
double loanAmount;
System.out.println("This program will compute the monthly payments and total payments for a loan amount on interest rates starting at 5%, incrementing by 1/8th percent up to 8%.");
//Formula to Calculate Monthly Interest Rate:
monthlyInterestRate = (annualInterestRate/1200);
//Formula to Calculate Monthly Payment:
monthlyPayment = (loanAmount*monthlyInterestRate);
//Formula To Calculate Annual Interest Rate:
annualInterestRate = (1-(Math.pow(1/(1 + monthlyInterestRate), numberOfYears * 12)));
//Formula To Calculate The Total Payment:
total = (monthlyPayment*numberOfYears*12);
while(true)
{
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
System.out.println("Interest Rate: " + annualInterestRate);
System.out.println("Monthly Payment: " + monthlyPayment);
System.out.println("Total Payment: " + total);
}
}
}
This does not compile and I'm not sure why. (Again, I'm a beginner)
The errors I am receiving are on the line that reads "double loanAmount = input.nextDouble();" AND the line that reads "double numberOfYears = input.nextDouble();".
The error for the first line says, "Duplicate local variable loanAmount".
The error for the second line says, "Multiple markers at this line
- Line breakpoint:Loans [line: 39] -
main(String[])
- Duplicate local variable numberOfYears"
Any feedback is appreciated.

The error you get is pretty much self explanatory. You have defined both "loanAmount" and "numberOfYears" two times in main. Either rename them or declare them only once.
If you are a beginner in coding I would recommend you use an IDE like Eclipse or Netbeans. They will point out compilation errors along with suggestions on how to fix them.

Easy enough to fix. So the issue is that in this segment:
System.out.println("Please enter in the loan amount.");
double loanAmount = input.nextDouble();
System.out.println("Please enter in the number of years.");
double numberOfYears = input.nextDouble();
You are re-defining your double variables loanAmount and numberOfYears, which is going to cause an error. Take out the "double" in both lines where they are used.
The other change you need to make is to intialize these variables at the top of your code. Change the lines where you initialize all of your double variables and set them equal to 0, for example:
double annualInterestRate = 0;
double numberOfYears = 0;
double loanAmount = 0;
When a variable has a call in a program, it must first be initialized. It doesn't matter what it's initialized to, since its end value will be determined by the program's actions, but it absolutely needs to be initialized at some point.
I made exactly these changes and the program compiled successfully.
Hope this helps!

Related

How to use System.out.printf() to display output of number to only two decimal places?

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);

Java Computing Monthly Payments Loops

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.

No idea whats wrong... (change machine)

I just started coding in java and I am working on a change machine-esk program. I know It can be condensed but Its part of the constraints.
It keeps out putting random change owed and quarter count...
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
double costVar, paidVar, amountOwed;//user defined
//defining the vale of US coins
final double quarterCoin = 0.25;
final double dimeCoin = 0.10;
final double nickelCoin = 0.05;
final double pennyCoin = 0.01;
//Variable for math stuff
double quarterAmountdec, dimeAmountdec, nickelAmountdec, pennyAmountdec;
short quarterAmountfin, dimeAmountfin, nickelAmountfin, pennyAmountfin;
Scanner keyboard = new Scanner(System.in);
//ask the user to input costs and amount payed (assuming the amount paid is > or = the cost of the item)
System.out.println("Enter Item Cost: ");
costVar=keyboard.nextDouble();
System.out.println("Enter Amount Paid: ");
paidVar=keyboard.nextDouble();
amountOwed = paidVar - costVar;//math for the changed owed
System.out.println("\nChange Owed: $" +amountOwed++);//displaying how much change the machine owes
//math to calculate the coins owed (involves intentional loss of accuracy
quarterAmountdec = amountOwed / quarterCoin;
quarterAmountfin = (short)quarterAmountdec;
//outputs coins owed
System.out.println("Quarters: " +quarterAmountfin++ );
}
}
Output:
Enter Item Cost:
2.34
Enter Amount Paid:
6.89
Change Owed: $4.55
Quarters: 22
The following line alters the amount owed after printing
System.out.println("\nChange Owed: $" +amountOwed++);
Thus when printing the amount owed looks fine, but internally the value is changed. I am personally unsure of the behaviour of calling ++ on a double, however I recommend removing the ++ and re-running your code.

How to implement a particular maths formula in Java?

package methods;
import java.util.Scanner;
/**
*
* #author Billy
*/
public class Methods {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double Loanamount; // Loan amount from user
double Aintrate; // User's annual interest rate
double months; // Number of months on loan
double monp; // Monthly payment
double Mintrate; // Monthly interest rate
double n; // The number of payments
// declare an instance of Scanner to read the datastream from the keyboard.
Scanner kb = new Scanner(System.in);
// Get user's loan amount
System.out.print("Please enter your total loan amount: ");
Loanamount = kb.nextDouble();
// Get user's interest rate
System.out.print("Please enter your annual interest rate as a decimal: ");
Aintrate = kb.nextDouble();
// Get user's number of months
System.out.print("Please enter the number of months left on your loan: ");
months = kb.nextDouble();
// Calculate montly interest rate
Mintrate = ((Aintrate / 12));
System.out.println("Your monthly interest rate is " + " " + Mintrate);
// Calculate number of payments
n = ((months * 12));
// Calculate monthly payment
My next job is to find out the monthly payment using this formula.
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where
M = monthly mortgage payment
P = The amount borrowed (Loanamount)
i = Monthly interest rate (Mintrate)
n = the number of payments
I tried the following but I just cant figure it out
monp = Loanamount [Mintrate(1+ Mintrate)^n] / [(1+ Mintrate)^n-1 ];
You need to use Math.pow effectivley here.
Try using following in your code
monp = Loanamount*(Mintrate*Math.pow((1+ Mintrate),n)) / (Math.pow((1+ Mintrate),n-1 ) ;
Math.pow is what you need instead of ^. Also you can't use [ or ]. You have to use parenthesis ( and ).
More math functions can be found at:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
The method for ^ is called Math.pow(double a, double b); in Java.
Where a is the number to be raised b times.
Your formula would then look like monp = Loanamount Math.pow((Mintrate(1+ Mintrate), n)) / (Math.pow((1+ Mintrate), n-1));
Reference
You need to call Math.pow(double,double)
OR you could import the required class as..
import static java.lang.Math.pow;
and then use pow() function

loan calculator that implements multiple methods

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.

Categories