gpt4 book ai didi

java - 为什么这个方法总是产生 0 作为它的返回值?

转载 作者:行者123 更新时间:2023-11-30 06:55:11 25 4
gpt4 key购买 nike

因此,无论方法的输入如何,我都会不断收到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com