打印循环的最后一行

时间:2014-06-16 23:47:14

标签: java loops for-loop

我要做的是以5 - DONE的增量打印结果。然后,只打印循环的最后一行。例如:如果z = 26,则打印z @ 5,10,15,20,25的结果。然后用z @ 26打印。我卡住了,无法解决。

for (int i = 1; i <= z; i++) {
    b = b + (b * y) + x + w;

    if (i % 5 == 0)
        //input 1
        System.out.println("In " + i + " years, IRA value: " + b);          

    //input 2 - value of IRA when retirement is reached
    System.out.println();

3 个答案:

答案 0 :(得分:1)

我不知道初始值为bxwy的原因是什么,所以我只是以某种方式初始化它们。

但我认为你想要这样的事情:

public class HelloWorld{

     public static void main(String []args){

        int z = 26;
        int b = 0;
        int x = 1;
        int w = 2;
        int y = 1;

        for (int i = 1;i<=z;i++) {
            b = b+(b*y)+x+w;
            if (i % 5 == 0)
                System.out.println("In " + i + " years, IRA value: " + b);          
        }

        System.out.print(z);
     }
}

输出:

In 5 years, IRA value: 93
In 10 years, IRA value: 3069
In 15 years, IRA value: 98301
In 20 years, IRA value: 3145725
In 25 years, IRA value: 100663293
26

答案 1 :(得分:0)

将您的条件更改为

if(i%5==0 || i==z)

答案 2 :(得分:0)

在if中添加或(|| i == z)将完成工作

for (int i = 1;i<=z;i++) {
    b = b+(b*y)+x+w;
    if (i%5==0 || i==z)

    //input 1
    System.out.println("In " + i + " years, IRA value: " + b);          

    //input 2 - value of IRA when retirement is reached
    System.out.println();

    //end
}