簡體   English   中英

在 if 語句之外使用變量

[英]Using variables outside of an if-statement

我不完全確定這在 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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM