麻烦在我的程序中使用for循环

时间:2015-04-07 21:56:25

标签: java loops

在我的代码中,我让用户输入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);
}

P.S。我仍在研究代码,但还没有完全完成。如果可能的话,我也想提供一些建议。

3 个答案:

答案 0 :(得分:1)

我注意到有些内容可能与您的代码完全无关。

首先,您将所有变量存储为双精度数,主要用于存储浮点数(即带小数位的数字)。代替double,使用int可能更好。

接下来你的for循环总是会在第1年到第15年循环15次。如果你希望这只是numOfYears次,你应该有一个与numOfYears相比的循环

for (years = 1; years <= numOfYears; years++) {
    //TODO
}

最后一些对于编码非常重要的事情,以及在教自己风格时容易忽视的事情。

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);
}

此缩进更清晰地显示了for循环中的内容,并有助于调试和可读性

答案 1 :(得分:1)

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

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

根据您的情况,您的代码正在向用户输入numOfyears,例如为3。你的循环来自(1..15),无论如何,因为你的循环的第二个参数是:15 >= years

您要找的是(1 .. numOfYears

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

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

答案 2 :(得分:0)

如果您只打印15年的利率,可以试试这个。

for (years = 1; numOfYears >= 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);

    if(years == 15) {
        break;
    }
}

如果用户输入任何大于15的数字,这将打印15年的利息,否则将打印所有年份的利率,如果用户输入数字&lt; 15。