在if语句之外使用变量
我不完全确定这是否可以在Java中使用,但是我如何使用在声明它的if语句之外的if语句中声明的字符串? 我真的很感激,如果有人能帮助我解决这个问题,我已经尝试了几个小时,似乎无法得到任何工作。
你不能因为范围的变化 。
如果在if
语句中定义变量,那么它只会在if
语句的范围内可见,其中包括语句本身和子语句。
if(...){ String a = "ok"; // a is visible inside this scope, for instance if(a.contains("xyz")){ a = "foo"; } }
您应该在范围外定义变量,然后在if
语句中更新其值。
String a = "ok"; if(...){ a = "foo"; }
您需要区分变量声明和赋值 。
String foo; // declaration of the variable "foo" foo = "something"; // variable assignment String bar = "something else"; // declaration + assignment on the same line
如果您尝试使用未指定值的声明变量,例如:
String foo; if ("something".equals(foo)) {...}
您将收到编译错误,因为该变量未分配任何内容,因为它仅被声明。
在您的情况下,您在条件块内声明变量
if (someCondition) { String foo; foo = "foo"; } if (foo.equals("something")) { ... }
所以它只在该区块内“可见”。 您需要在外面移动该声明并以某种方式为其赋值,否则您将得到条件赋值编译错误。 一个例子是使用else
块:
String foo; if (someCondition) { foo = "foo"; } else { foo = null; }
或者在声明中指定默认值(null?)
String foo = null; if (someCondition) { foo = "foo"; }