I'm learning Java on Codecademy and recently completed a project that calculates monthly payments for a car loan. The problem is that I don't understand the solution, and no one has responded to my question about it on the Codecademy forum.
Why are the instance variables created in the main method scope instead of just after the class has been declared? We haven’t seen any examples of this prior to this project and I don’t understand.
Here is the code:
//Calculates monthly car payment
public class CarLoan {
//Why aren't the variables created here rather than in the main method?
public static void main(String[] args) {
int carLoan = 10000;
int loanLength = 3;
int interestRate = 5;
int downPayment = 2000;
if (loanLength <=0 || interestRate <=0) {
System.out.println("Error! You must take out a valid car loan.");
} else if (downPayment >= carLoan) {
System.out.println("The car can be paid in full.");
} else {
int remainingBalance = carLoan - downPayment;
int months = loanLength * 12;
int monthlyBalance = remainingBalance / months;
int interest = (monthlyBalance * interestRate) / 100;
int monthlyPayment = monthlyBalance + interest;
System.out.println(monthlyPayment);
}
}
}