[英]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.