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

查看:38
本文介绍了在 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天全站免登陆