2014-12-05 20 views
0

我想返回result變量,但eclipse標記爲return result;部分並且說Create local variable 'result'我該如何使該方法返回到該循環中的變量

方法,我寫道:

public E getFromResults(int o) 
{ 
    Node tempNode = head; 
    for(int i=1; i<= size; i++) 
    { 
     if(i==o) 
     { 
      E result = (E) tempNode.getElement(); 
      break; 
     } 

     tempNode=tempNode.getNext(); 
    } 

    return result; 
} 

好吧,我做了如下圖所示所以它現在的工作謝謝EVERONE誰回答他們的幫助:

public E getFromResults(int o) 
{ 
    Node tempNode = head; 
    for(int i=1; i<= size; i++) 
    { 
     if(i==o) 
      break; 

     tempNode=tempNode.getNext(); 
    } 

    E result = (E) tempNode.getElement(); 


    return result; 
} 

回答

1

result變量處於if塊的範圍內,因此它不在其外。改爲在for循環外聲明result

0

你必須把變量聲明循環之外,如果。聲明方式:

public E getFromResults(int o) 
{ 
    Node tempNode = head; 
    E result = null; 
    for(int i=1; i<= size; i++) 
    { 
     if(i==o) 
     { 
      result = (E) tempNode.getElement(); 
      break; 
     } 

     tempNode=tempNode.getNext(); 
    } 

    return result; 
} 

因爲它不能保證它會經過循環,如果是這樣的結果變量不能在某一時刻存在。

1
public E getFromResults(int o) 
{ 
    E result = null; 

    Node tempNode = head; 
    for(int i=1; i<= size; i++) 
    { 
     if(i==o) 
     { 
      result = (E) tempNode.getElement(); 
      break; 
     } 

     tempNode=tempNode.getNext(); 
    } 

    return result; 
} 

這是由於變量的範圍。您從嵌套的if語句中初始化變量result,該語句本身在for語句中。這意味着在if聲明之外沒有任何內容可以看到或訪問您的result變量 - 即。該代碼塊爲local

如果你是移動的result到初始化if塊外但仍在for塊內,這將使它所以裏面的一切都在forif塊可以使用它,但你還是沒能returnresult因爲return語句在兩個塊之外。

有時你會使用變量作用域,也就是說,如果一段代碼需要一些臨時變量和/或永遠不能從代碼塊外部訪問的變量。

相關問題