The Problem
You're mixing static and non-static functionality in some pretty odd ways. Here's what's happening in your code:
private static double MonthlyInterest;
You create a static variable on your class. Since it's a primitive double
, it defaults to storing 0
. Also, variable names should start with a lower-case letter. This should be monthlyInterest
. It won't break anything, but it's a standard Java convention to distinguish class names from variable names.
calculateMonthlyInterest();
You call the calculateMonthlyInterest()
method.
double MonthlyInterest = (accountBalance * annualInterestRate);
return MonthlyInterest;
You calculate the monthly interest, store it in a new variable, and return it. Note that your static MonthlyInterest
variable is not updated by this code. Instead, the local variable that you created "shadows" the static variable, and takes precedent over it.
calculateMonthlyInterest();
System.out.println(MonthlyInterest)
Your throw away your return value having never used it, and then print out the static MonthlyInterest
that was never changed from its initial value of zero.
Here are two different approaches that you can take to make your code work:
With static variables
public class BankAccount {
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
private static double monthlyInterest;
public static void main(String[] args) {
calculateMonthlyInterest();
System.out.println(monthlyInterest);
}
public static void calculateMonthlyInterest() {
monthlyInterest = (accountBalance * annualInterestRate);
}
}
With local variables
public class BankAccount {
private static final double annualInterestRate = 1.5;
private static double accountBalance = 150;
public static void main(String[] args) {
double monthlyInterest = calculateMonthlyInterest();
System.out.println(monthlyInterest);
}
public static double calculateMonthlyInterest() {
return accountBalance * annualInterestRate;
}
}