Returning a value across classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anon538
    New Member
    • Sep 2007
    • 23

    Returning a value across classes

    I have a class named collect.java that looks like this:
    Code:
    public class collect {
    	public int returnX() {
    		int x=5;
    		return x;
    	}
    }
    I also have a main class-
    Code:
    public class testcollect {
        public static void main(String[] args) {
            collect collector = new collect();
            collector.returnX();
            System.out.println(x);
        }
    }
    I was expecting the testcollect class to simply print out 5. Yet I get the error message "cannot find variable x". Please help.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Read exactly what the message says. There is no variable x in your main() program. The variable x is not returned by your function - only its value. In order to catch that value, you need to store it in your own variable. If you change your main to:

    [CODE=java]//...
    int x = collector.retur nX();
    System.out.prin tln(x);
    //...[/CODE]

    it will work as expected.

    Comment

    • anon538
      New Member
      • Sep 2007
      • 23

      #3
      Thank you! I feel so stupid for not thinking of that.

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        You're welcome. Functions returning values is a fundamental concept in programming, so make sure you understand it well (and understand functions that don't return values as well).

        Comment

        Working...