在if语句之外使用变量 [英] Using variables outside of an if-statement

查看:166
本文介绍了在if语句之外使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您不能因为可变范围.

如果您在if语句内定义变量,则该变量将仅在if语句的范围内可见,该范围包括该语句本身以及子语句.

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";
   }
}

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

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

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

这篇关于在if语句之外使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆