问题描述
在 Java 中,可以在 for
循环的初始化部分声明一个变量:
In Java it is possible to declare a variable in the initialization part of a for
-loop:
for ( int i=0; i < 10; i++) {
// do something (with i)
}
但是对于 while
语句,这似乎是不可能的.
But with the while
statement this seems not to be possible.
我经常看到这样的代码,当每次迭代后都需要更新 while 循环的条件时:
Quite often I see code like this, when the conditional for the while loop needs to be updated after every iteration:
List<Object> processables = retrieveProcessableItems(..); // initial fetch
while (processables.size() > 0) {
// process items
processables = retrieveProcessableItems(..); // update
}
在 stackoverflow 上,我至少找到了一个解决方案来防止获取可处理项目的重复代码:
Here on stackoverflow I found at least a solution to prevent the duplicate code of fetching the processable items:
List<Object> processables;
while ((processables = retrieveProcessableItems(..)).size() > 0) {
// process items
}
但是变量仍然需要在while循环之外声明.
But the variable still has to be declared outside the while-loop.
所以,由于我想保持我的变量范围干净,是否可以在 while 条件中声明一个变量,或者对于这种情况是否有其他解决方案?
So, as I want to keep my variable scopes clean, is it possible to declare a variable within the while conditional, or is there some other solution for such cases?
推荐答案
您可以使用 for
循环编写 while
循环:
You can write a while
loop using a for
loop:
while (condition) { ... }
与
for (; condition; ) { ... }
由于 基本语句声明 是可选的:
BasicForStatement:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
同样,您可以将 while
循环重写为 for
循环:
Similarly, you can just rewrite your while
loop as a for
loop:
for (List<Object> processables;
(processables = retrieveProcessableItems(..)).size() > 0;) {
// ... Process items.
}
请注意,某些静态分析工具(例如 eclipse 4.5)可能要求将初始值分配给 processables
,例如列表processables = null.根据 JLS 的说法,这是不正确的;如果变量最初未赋值,我的 javac
版本不会抱怨.
Note that some static analysis tools (e.g. eclipse 4.5) might demand that an initial value is assigned to processables
, e.g. List<Object> processables = null
. This is incorrect, according to JLS; my version of javac
does not complain if the variable is left initially unassigned.
这篇关于是否可以在有条件的情况下在 Java 中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!