0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.