初学者循环GUI



我必须制作这个GUI,它是一个CD计算器。

I put in the Initial investment ($): e.g. 2000
the Annual interest rate (%): e.g. (8%)
Ending value ($): e.g. 5000

然后程序在jLabel上输出:所需的年数为"12"(例如)

我需要做一个临时循环和一个计数器。

我从3个文本字段中获取了文本,然后添加了年利率为%的initialInvestment,但在循环和计数器方面遇到了问题?

int initialInvestment, endValue, cdvalue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
cdValue = initialInvestment + (initialInvestment * annualRate);
double a = cdValue;
while (a <= endValue){
    a = a++;
    yearsOutput.setText("The required year needed is: " + a);
}

您只需在循环的每次迭代中向a添加1。因此,以这种方式需要几千次迭代才能满足循环需求。

你要做的是每年不断增加利息,同时计算年份,并且只在循环完成后更新输出。

int initialInvestment, endValue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
// First year interest is counted here.
cdValue = initialInvestment + (initialInvestment * annualRate);
int years = 1;
while (cdValue < endValue){
  cdValue = cdValue + (cdValue * annualRate);
  years++;
}
yearsOutput.setText("The required year needed is: " + years);

最新更新