[英]define variable with optional class type in if else statement
我需要根據是否設置了參數(opath)來更改類/流類型,但是當我在if-else語句中聲明時,netbeans抱怨找不到變量oos。
我不明白這一點,因為var oos總是被設置的,而且它永遠都不會被定義?
if(_param.get("opath") != null) {
FileOutputStream oos = new FileOutputStream(_param.get("opath").toString());
} else {
OutputStream oos = csocket.getOutputStream();
}
do something with oos...
將您的代碼更改為關注
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
//do something with oos
它只涉及范圍,並使對象可用於您要使用它的代碼
局部變量的范圍受其定義塊的限制,在這種情況下為if
or else
塊,因此無法從外部訪問它。
您可以將其移出:
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
do something with oos...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.