在java中将变量从if传递给else

时间:2017-02-12 22:34:42

标签: java if-statement conditional-statements

a循环中定义if变量,需要传递else if循环中更新的值。示例:

if(document.getVersionIdentifier().getValue().equals("00"))
{
    String a=attrs.put(CREATED_BY, shortenFullName(document
                            .getCreatorFullName()));
    // Value a = USer1
}
else if(document.getVersionIdentifier().getValue().equals("01"))
{
    String b = attrs.put(document,a);
    // Need value of b to be User1
}

1 个答案:

答案 0 :(得分:2)

首先,你的问题毫无意义。如果执行了if语句,则else if将被忽略,因此将if正文中的任何数据传递给else if正文都无关紧要。

但是,您可以做的是将else if更改为单独的if语句,并在a机构之外定义if。原则上这可能看起来像这样 - 需要根据你真正想要的东西进行调整(从你的问题中不清楚)。

String a = null;
if(document.getVersionIdentifier().getValue().equals("00"))
{
    a = attrs.put(CREATED_BY, shortenFullName(document.getCreatorFullName()));
    // Value a = User1
}

// The value of a can be either null or set during the if statement above.
// If a has a value the next if statement will always be false so the value of a
// will be always null if the next if statement is true.
if(document.getVersionIdentifier().getValue().equals("01"))
{
    String b = attrs.put(document,a);
    // Need value of b to be User1
}