如何在代码执行了一定次数后停止代码运行?

huangapple go评论73阅读模式
英文:

how to stop the code when the code has executed a certain amount of times?

问题

public void runSequence4(Intake feed, int n){
    for(int x = 1; x <= n; x++){
        int value = (x % 2 == 0) ? -1 : 1;
        feed.give(value);
    }
}
英文:

Name: runSequence4
Input: Intake feed, int n
Output: none
Action: Takes in an intake object and calls the method give(). It first passes the number 1 into
give and then alternates between -1 and 1. It does this n number of times.

How do I stop the loop when the code executes it "N" times?

This is what i have so far

public void runSequence4(Intake feed, int n){
    for(int x = 1;  ????     ; x = (x * -1)){
        feed.give(x);
    }
}

答案1

得分: 1

只需添加一个变量 i 以存储当前迭代,并测试它是否超过了 n

public void runSequence4(Intake feed, int n){
    for(int x = 1, i = 0; i < n; x = (x * -1), i++){
        feed.give(x);
    }
}
英文:

Just add a variable i to store the current iteration and test whether it has exceeded n

public void runSequence4(Intake feed, int n){
    for(int x = 1, i = 0; i &lt; n; x = (x * -1), i++){
        feed.give(x);
    }
}

huangapple
  • 本文由 发表于 2020年10月11日 05:28:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64298489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定