简体   繁体   中英

How can i make this method return to that variable in that loop

I want to return to result variable but eclipse marks that return result; part and says Create local variable 'result' .

The method i wrote:

 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;
 }

Okay i did it as shown below so it is working now thank you everone who answered for their help:

 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;
 }
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;
 }

This is due to variable scope. You initialized your variable result from within a nested if statement, which itself is in a for statement. This means nothing outside the if statement can see or access your result variable -- ie. it is local to that code block.

If you were to move the initialization of result to outside the if block but still inside the for block, that would make it so everything inside both the for and if blocks can use it, however you still could not return the result variable since the return statement is outside both blocks.

Sometimes you will use variable scope to your advantage, ie. if a block of code requires some variable that are temporary and/or should never be accessed from outside the code block.

The result variable is within the scope of the if block and therefore is not present outside it. Declare result outside the for loop instead.

You must put the variable declaration outside the loop and if. Declare that way:

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;
}

Because it is not guaranteed that it will go through the loop and if so the result variable can never exist at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM