所以无论方法输入如何,我都会继续收到this.app.router...
的答案。当我输入0
个月,6
储蓄金额和100
利率时,它应该会给我0.05
,但回复是608.81
。我觉得它可能是我的0
循环或我设置的参数搞乱它。我已经尝试了关于for
循环的所有想法。这是代码:
for
答案 0 :(得分:3)
您将以下变量传递给您的方法:
public static double compoundValueMethod(double savingAmount,
double annualInterestRate,
int NumberOfMonth)
注意但是在方法中使用静态变量numberOfMonth
而不是传递的NumberOfMonth
参数(Java中的变量名称区分大小写)。默认情况下,numberOfMonth
初始化为0
,因此未输入for循环,方法返回0.
您应该消除静态变量并仅使用局部变量。如果你首先做到了这一点,你会得到一个编译错误,这将使你更容易找到你的错误。
答案 1 :(得分:1)
你不需要静态变量。 更新代码如下
公共课FifthAssignment2 {
public static double compoundValueMethod(double savingAmount, double annualInterestRate, int numberOfMonth) {
{
DecimalFormat formatter = new DecimalFormat(".00");
double sixthMonth = 0.0;
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 0; i < numberOfMonth; i++) {
sixthMonth = ((savingAmount+sixthMonth) * (1 + monthlyInterestRate));
}
}
return sixthMonth;
}
}
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00");
int numberOfMonth;
String NOM = JOptionPane.showInputDialog("How many months? ");
numberOfMonth = Integer.parseInt(NOM);
double savingAmount;
String SA = JOptionPane.showInputDialog("What is your savings amount? ");
savingAmount = Double.parseDouble(SA);
String AIR = JOptionPane.showInputDialog("What is the annual interest rate? "); // Window
// pops
// up
double annualInterestRate;
annualInterestRate = Double.parseDouble(AIR);
{
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is "
+ compoundValueMethod(savingAmount, annualInterestRate, numberOfMonth));
}
}
}
答案 2 :(得分:0)
使用NumberOfMonth
代替numberOfMonth
for (int i = 0; i < NumberOfMonth; i++) {
sixthMonth = ((savingAmount+sixthMonth) * (1 + monthlyInterestRate));
}
或内部方法可以指定
numberOfMonth=NumberOfMonth;