Q:

How to use a value which you are getting from a for loop as return value for the same method

I am trying to create a method which return a int value(in my case locationY is the value which i wanted to return) which i am getting from a variable which is declared and initialized inside a for loop in thge same method. I tried two ways to do so. In my 1st try code i got error which says "locationY cannot be resolved to a variable". Then in my 2nd try i tried to return the locationY from inside the for loop. But again got an error which says that "This method must return a result of type int". Can anyone please tell me how can i use the varable present inside a for loop to the same method. 
1st Try -
 public int getvalueY() throws InterruptedException{
  for(int i=0; i<20;i++){
      PointerInfo pointer = MouseInfo.getPointerInfo();
      Point point = pointer.getLocation();
      int locationY = (int)point.getY();
      Thread.sleep(2000);
  }
     return locationY;
}

2nd Try - 
 public int getvalueY() throws InterruptedException{
  for(int i=0; i<20;i++){
      PointerInfo pointer = MouseInfo.getPointerInfo();
      Point point = pointer.getLocation();
      int locationY = (int)point.getY();
      Thread.sleep(2000);
      return locationY;
   }
 }

A:

In your first try, you're declaring locationY in the for loop.
So this variable is only known within the loop and is unknown in the line with the return statement.
If you declare & initialize it outside the loop, you can use it in both places (in- and outside the loop:
public int getvalueY() throws InterruptedException{
  int locationY = 0;
  for(int i=0; i<20;i++){
      PointerInfo pointer = MouseInfo.getPointerInfo();
      Point point = pointer.getLocation();
      locationY = (int)point.getY();
      Thread.sleep(2000);
  }
   return locationY;
}

I'd recommend to look up scoping for Java i. e. the visibility of variables in Java.

