在if语句之外使用变量 [英] Using Variables Outside of an if Statement

查看:180
本文介绍了在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? I would really appreciate it if anyone could help me out with this, I've been trying for hours and can't seem to get anything to work.

推荐答案

你不能因为变量范围

如果在 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天全站免登陆