问题描述
所以我在某个地方声明了一个变量并对其进行了初始化.现在稍后我需要在它仍然为正时使用它来循环,所以我需要减少它.对我来说,循环使用条件和减量需要 for 但我们缺少初始化的第一部分.但我不需要初始化任何东西.那么我该如何以一种好的方式来解决这个问题.
so i declare a variable some where and initialize it. now later on i need to use it to loop while its still positive so i need to decrement it. to me looping using a condition and a decrement calls for a for but for it we are missing the first part the initialization. but i don't need to initialize anything. so how do i go about that in a nice way.
for (space = space; space > 0; space--)//my first way to do it but ide doesnt like it
第二种方式:
for (; space > 0; space--)//my friend recommended me this way but looks kind weird
是否有更多方法可以让我拥有一个只有条件和递增/递减的循环?
are there more ways for me to have a loop with only condition and increment/decrement?
p.s 拼写检查不知道递减"是一个词.我很确定它是......
p.s spell check doesn't know that "decrement" is a word. i'm pretty sure it is...
推荐答案
另一种方法是:
integer i = 10; while(--i>0) { system.out.println(i); }
当 i 为 0 而条件为假时...所以.. 它将从 9 打印到 1(9 项)
when i is 0 while condition is false... so.. it will print from 9 to 1 (9 items)
integer i = 10; while(i-->0) { system.out.println(i); }
将从 9 打印到 0...(10 项);
will print from 9 to 0... (10 items);