我需要更改类/流类型,这取决于是否设置了param (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...
发布于 2018-08-22 20:02:07
将代码更改为
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
//do something with oos
它只是关于范围和使对象对您想要使用的代码可用。
发布于 2018-08-22 20:02:17
本地变量的范围有限--它的定义块,在本例中是if
或else
块,因此无法从外部访问。
你可以搬出去:
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
do something with oos...
发布于 2018-08-22 22:14:57
您不会遇到使用三元算子的这个问题,它是“if-然后-else语句的缩写”:
OutputStream oos = _param.get("opath") != null ?
new FileOutputStream(_param.get("opath").toString()) :
csocket.getOutputStream();
在这种情况下,oos
会立即声明和初始化。
此外,这还允许定义变量oos
,甚至是final
,它不使用常规的if-else-语句。
https://stackoverflow.com/questions/51978127
复制相似问题