gpt4 book ai didi

java - 在我的程序中使用 for 循环时出现问题

转载 作者:行者123 更新时间:2023-12-02 04:48:01 27 4
gpt4 key购买 nike

在我的代码中,我让用户输入 3 个内容,对于第三个输入,我要求输入年数。但是,在我的 for 循环中,我无法使用要求用户输入的变量。例如,如果用户输入“3”,我的代码将执行15年(这是最大值)。

double yearInvest;
double interRate;
double numOfYears = 3;
double amountBeforeTotal;
double amountTotal;
double years;

System.out.println("Compound Interest \n");
System.out.println("This program will print out a title table that will "
+ " display the amount of a yearly investment over a period of "
+ " up to 15 years. \n");

Scanner input = new Scanner(System.in);
System.out.println("Enter the yearly investment:");
yearInvest = input.nextDouble();
System.out.println("Enter the interest rate (%):");
interRate = input.nextDouble();
System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();

for (years = 1; 15 >= years; years++) {
System.out.format("%-4s %22s %12s %8s \n ", "Year", "Amount in Account",
"Interest", "Total");

amountTotal = (yearInvest * (interRate / 100)) + yearInvest;
System.out.format("%-4.1f", years);
System.out.format("%18.2f", yearInvest);
System.out.format("%14.2f", interRate);
System.out.format("%15.2f", amountTotal);
}

附注我仍在编写代码,尚未完全完成。如果可能的话,我也希望得到一些建议。

最佳答案

System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();

for (years = 1; 15 >= years; years++)

您的代码正在获取用户输入的numOfyears,对于您的情况,例如为 3。无论如何,你的循环都是从 (1..15) 开始的,因为你的循环的第二个参数是:15 >= 年

您要查找的是 (1..numOfYears)

System.out.println("Enter the number of years:");
numOfYears = input.nextDouble();

for (years = 1; years <= numOfYears; years++)
//...more code

关于java - 在我的程序中使用 for 循环时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29502085/

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