因此,无论该方法的输入如何,我都会不断收到 0
的答案。当我输入 6
个月、100
储蓄金额和 0.05
利率时,它应该给我 608.81
但响应是0
。我觉得这可能是我的 for 循环或我设置的参数弄乱了它。我已经尝试了所有我能想到的有关 for
循环的方法。代码如下:
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class FifthAssignment2 {
static double savingAmount = 0.0; // the 2 given static doubles
static double annualInterestRate = 0.0;
static int numberOfMonth;
static double sixthMonth = 0.0;;
public static double compoundValueMethod(double savingAmount, double annualInterestRate, int NumberOfMonth) {
{
DecimalFormat formatter = new DecimalFormat(".00");
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);
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
annualInterestRate = Double.parseDouble(AIR);
{
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is "
+ compoundValueMethod(savingAmount, annualInterestRate, numberOfMonth));
}
}
}
最佳答案
您将以下变量传递给您的方法:
public static double compoundValueMethod(double savingAmount,
double annualInterestRate,
int NumberOfMonth)
请注意,请在方法中使用静态变量 numberOfMonth
,而不是传递的 NumberOfMonth
参数(Java 中的变量名称区分大小写)。 numberOfMonth
默认初始化为 0
,因此不会进入 for 循环并且该方法返回 0。
您应该消除静态变量并仅使用局部变量。如果您一开始就这样做,您会收到编译错误,这将使您更容易找到错误。
关于java - 为什么这个方法的返回值总是0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619822/