英文:
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 < n; x = (x * -1), i++){
feed.give(x);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论