returning a value from a method to another method

前端 未结 8 582
时光取名叫无心
时光取名叫无心 2021-01-19 14:42

Can somebody tell me why the value returned is 3 and not 8. Doesn\'t the return x statement from the addFive method change the value of x

相关标签:
8条回答
  • 2021-01-19 14:47

    Because you're simply not using the computation of your function. It doesn't change value of x, it returns new value.

    You should do something like:

    int y = addFive(x);
    
    0 讨论(0)
  • 2021-01-19 15:03

    You are calling the method addFive(int x) with x, but not assigning the returned value to anything. So, inside main()'s scope x remains as before, 3 - which is what is being printed. So, you can either store the returned value to x itself:

    x = addFive(x);
    

    or make the function call within print statement:

    System.out.println("x = " + addFive(x));
    
    0 讨论(0)
  • 2021-01-19 15:03

    The method does return a value, but you have to set the value to a variable too when you return it, or else how would it know which variable you want to return the value to? You can have 10 variable, and if you just call the method, how will it know which variable to return the number to? That's why you have to set the returning number it to a variable like this:

    x = addFive(x);
    
    0 讨论(0)
  • 2021-01-19 15:08

    You have to set the returned value to a variable, otherwise it is lost and you are retrieving the value of "x" in your main method. Do this instead to capture the return value.

       public static void main(String[] args) {
           int x=3;
           x = addFive(x);
           System.out.println("x = " + x);
       }
    

    If you only want to see the returned value and not store it, you can even put the function call inside the System.out.println.

       public static void main(String[] args) {
           int x=3;
           System.out.println("x = " + addFive(x));
    
       }
    
    0 讨论(0)
  • 2021-01-19 15:08

    Like everyone else is saying, you need to assign your return value. Because you're doing "addFive(x)" instead of "x=addFive(x);" you're just printing the instance of "x" in main, and not ever getting the value that your function returns.

    This is because "x" in your main function is an instance variable, and your "x" in addFive() is a local variable. These are not the same variable, even if they have the same name. This might clarify a bit - http://www.tutorialspoint.com/java/java_variable_types.htm

    0 讨论(0)
  • 2021-01-19 15:11

    You want x=addFive(x); rather than just addFive(x). Calling addFive(x) on it's own does not apply the returned value to any variable.

    0 讨论(0)
提交回复
热议问题