Using variables outside of an if-statement

后端 未结 2 2051
甜味超标
甜味超标 2020-12-04 00:08

I\'m not entirely sure if this is possible in Java, but how would I use a string declared in an if-statement outside of the if-statement it was declared in?

2条回答
  •  囚心锁ツ
    2020-12-04 01:02

    You can't because of variable scope.

    If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements.

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

    You should define the variable outside the scope and then update its value inside the if statement.

    String a = "ok";
    if(...){
        a = "foo";
    }
    

提交回复
热议问题