[英]Is it possible to declare a variable within a Java while conditional?
在 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 上,我至少找到了一個解決方案來防止獲取可處理項目的重復代碼:
List<Object> processables;
while ((processables = retrieveProcessableItems(..)).size() > 0) {
// process items
}
但是變量仍然必須在 while 循環之外聲明。
所以,因為我想保持我的變量范圍干凈,是否可以在 while 條件中聲明一個變量,或者對於這種情況是否有其他解決方案?
您可以使用for
循環編寫while
循環:
while (condition) { ... }
是相同的
for (; condition; ) { ... }
因為語句聲明基本括號中的所有三個位都是可選的:
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
版本不會抱怨。
不,這是不可能的。
它也沒有太多意義:不像你可以設置“循環變量”的初始狀態的for
循環,在while
循環中你測試現有變量的值,類似於條件檢查 for
循環。
當然,如果您擔心變量“泄漏”到代碼的其他部分,您可以將整個事物包含在額外的范圍塊中:
{
/*declare variable here*/
while(...){...}
}
或者,將while
循環轉換為for
循環。
做一個/一會兒:
String value;
do {
value = getValue();
...your processing
} while (value != null && !value.isEmpty());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.