使用if语句之外的变量

Kra*_*ynz 2 java scope if-statement

我不完全确定这在Java中是否可行,但是我如何使用在声明的if语句之外的if语句中声明的字符串?

res*_*a87 12

你不能因为范围变化.

如果在if语句中定义变量,那么它只会在if语句的范围内可见,其中包括语句本身和子语句.

if(...){
   String a = "ok";
   // a is visible inside this scope, for instance
   if(a.contains("xyz")){
      a = "foo";
   }
}
Run Code Online (Sandbox Code Playgroud)

您应该在范围外定义变量,然后在if语句中更新其值.

String a = "ok";
if(...){
    a = "foo";
}
Run Code Online (Sandbox Code Playgroud)


Yan*_*hon 8

您需要区分变量声明赋值

\n\n
String foo;                     // declaration of the variable "foo"\nfoo = "something";              // variable assignment\n\nString bar = "something else";  // declaration + assignment on the same line\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您尝试使用未分配值的声明变量,例如:

\n\n
String foo;\n\nif ("something".equals(foo)) {...}\n
Run Code Online (Sandbox Code Playgroud)\n\n

您将收到编译错误,因为该变量未分配任何内容,因为它只是声明了。

\n\n

在您的情况下,您在条件块内声明变量

\n\n
if (someCondition) {\n   String foo;\n   foo = "foo";\n}\n\nif (foo.equals("something")) { ...\xc2\xa0}\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以它只在该块内“可见”。您需要将该声明移到外部并以某种方式为其分配一个值,否则您将收到条件赋值编译错误。一个例子是使用else块:

\n\n
String foo;\n\nif (someCondition) { \n   foo = "foo";\n} else {\n   foo = null;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或在声明时指定默认值(null?)

\n\n
String foo = null;\n\nif (someCondition) {\n   foo = "foo";\n}\n
Run Code Online (Sandbox Code Playgroud)\n