没有索引声明的for循环

for loop without index declaration(没有索引声明的for循环)

本文介绍了没有索引声明的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在某个地方声明了一个变量并对其进行了初始化.现在稍后我需要在它仍然为正时使用它来循环,所以我需要减少它.对我来说,循环使用条件和减量需要 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);

这篇关于没有索引声明的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:没有索引声明的for循环

基础教程推荐