[英]define variable with optional class type in if else statement
I need to change the class / stream type depending on whether a param (opath) is set, but when I declare in an if-else statement, netbeans complains that the variable oos cannot be found. 我需要根据是否设置了参数(opath)来更改类/流类型,但是当我在if-else语句中声明时,netbeans抱怨找不到变量oos。
I don't understand this as the var oos is always set and there's no way that it is ever undefined ?? 我不明白这一点,因为var oos总是被设置的,而且它永远都不会被定义?
if(_param.get("opath") != null) {
FileOutputStream oos = new FileOutputStream(_param.get("opath").toString());
} else {
OutputStream oos = csocket.getOutputStream();
}
do something with oos...
Change you code to following 将您的代码更改为关注
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
//do something with oos
It is just about scope and making the object available to the code where you want to use it 它只涉及范围,并使对象可用于您要使用它的代码
local varibales's scope is limited it's definition block, in this case, the if
or else
block, so it's unaccessible from outside. 局部变量的范围受其定义块的限制,在这种情况下为
if
or else
块,因此无法从外部访问它。
you can move it out: 您可以将其移出:
OutputStream oos;
if(_param.get("opath") != null) {
oos = new FileOutputStream(_param.get("opath").toString());
} else {
oos = csocket.getOutputStream();
}
do something with oos...
You wouldn't encounter this issue using the ternary operator which is a " shorthand for an if-then-else statement ": 使用三元运算符不会遇到此问题,该运算符是“ if-then-else语句的缩写 ”:
OutputStream oos = _param.get("opath") != null ?
new FileOutputStream(_param.get("opath").toString()) :
csocket.getOutputStream();
In this case oos
is declared and initialized at once. 在这种情况下,立即声明并初始化
oos
。
Additionally this allows to define the variable oos
even final
which isn't possbile using the regular if-else-statement. 另外,这允许使用常规的if-else语句来定义变量
oos
甚至final
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.