Is it possible to declare a variable within a Java while conditional?

好久不见. 提交于 2019-12-06 23:07:10

问题


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)
}

But with the while statement this seems not to be possible.

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
}

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
}

But the variable still has to be declared outside the while-loop.

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?


回答1:


You can write a while loop using a for loop:

while (condition) { ... }

is the same as

for (; condition; ) { ... }

since all three bits in the brackets of the basic for statement declaration are optional:

BasicForStatement:
    for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

Similarly, you can just rewrite your while loop as a for loop:

for (List<Object> processables;
     (processables = retrieveProcessableItems(..)).size() > 0;) {
  // ... Process items.
}

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.




回答2:


No it's not possible.

It doesn't really make too much sense either: unlike a for loop where you can set up the initial state of the "looping variable", in a while loop you test the value of an existing variable, akin to the conditional check of the for loop.

Of course, if you're concerned about variables "leaking" into other parts of your code, you could enclose the whole thing in an extra scope block:

{
   /*declare variable here*/
   while(...){...}
}

Alternatively, convert the while loop into a for loop.



来源:https://stackoverflow.com/questions/38766891/is-it-possible-to-declare-a-variable-within-a-java-while-conditional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!