gpt4 book ai didi

java - 是否可以在有条件的情况下在 Java 中声明变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:23 25 4
gpt4 key购买 nike

在 Java 中,可以在 for 循环的初始化部分声明一个变量:

for ( int i=0; i < 10; i++) {
// do something (with i)
}

但是对于 while 语句,这似乎是不可能的。

当 while 循环的条件需要在每次迭代后更新时,我经常看到这样的代码:

List<Object> processables = retrieveProcessableItems(..); // initial fetch
while (processables.size() > 0) {
// process items
processables = retrieveProcessableItems(..); // update
}

在 stackoverflow 上我至少找到了 a solution防止获取可处理项目的重复代码:

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

但变量仍然必须在 while 循环之外声明。

因此,由于我想保持我的变量范围干净,是否可以在 while 条件中声明一个变量,或者对于这种情况是否有其他解决方案?

最佳答案

你可以写一个while使用 for 循环循环:

while (condition) { ... }

相同
for (; condition; ) { ... }

因为 basic for statement declaration 括号中的所有三个位是可选的:

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

同样,你可以重写你的 while循环为 for循环:

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

请注意,某些静态分析工具(例如 eclipse 4.5)可能要求将初始值分配给 processables ,例如List<Object> processables = null .根据 JLS,这是不正确的;我的版本 javac如果变量最初未分配,则不会提示。

关于java - 是否可以在有条件的情况下在 Java 中声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38766891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com