2017-02-12 51 views
-2

定義爲a變量在if循環中並且需要傳遞在else if循環中更新的值。例如:從java中傳遞變量if到else

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 
} 

回答

2

首先,你的問題沒有意義。如果執行if語句,則else if將被忽略,因此將if正文中的任何數據傳遞給else if正文是不相關的。

然而,你可以做的是改變else if到一個單獨的if聲明並定義aif機構。原則上,這可能看起來像這樣 - 需要根據你真正想要的來調整(從你的問題中不清楚)。

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 
} 
+3

請注意,代碼沒有任何意義,如寫入;如果第一個'if'被執行,第二個不會被執行,除非getVersionIdentifier()。getValue()'在被調用兩次時能夠返回不同的值。所以'a'永遠不能是'null'以外的任何東西。所以這絕對需要調整。 – ajb

+0

同意。增加了更多的代碼文檔以使其清晰。 –