I have a for loop with length 20.
I have a height of 800. I want to put a value 20 times separated by the same gap.
For example:
800 / 20 = 40
Every 40 I want to println the value. 40, 80, 120, 160... until 800.
I don't understand how to do this inside a loop. My approach is wrong and does not have the same gap between them.
for (int i = 0; i < array.size(); i++) {
int posY = (i != 0) ? 800/ i : 800;
println(posY);
}
Well there are imho three different aproaches. Which one depends on what else you need to do with i.
1) Use i directly:
for (int i = 40; i <= 800; i+=40) {
println(i);
}
This asumes that you don't need nothing else but the 20 numbers.
2) you need to count:
for (int i = 1; i <= 20; i++){
println(i*40);
}
2b) application eg. if 800 is in a variable:
for (int i = 1; i <= 800/40; i++){
println(i*40);
}
This assumes you need to track which step you are taking and want to do something with i.
3) you need the steps inbetween for something
for (int i = 1; i <= 800; i++) {
if(0 == i%40 ){ //if the rest of i/40 gives 0
println(i);
}
}
This last version prints the same numbers but still i goes over all values inbetween.
Plus if you have an array you need to iterate over: replace the 800 with "array.length -1"
OR replace the "<=" by "<" and use "array.length" above.
(And well there are a whole lot of variations of this)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.