returning a value from a method to another method

前端 未结 8 645
时光取名叫无心
时光取名叫无心 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 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));
    
       }
    

提交回复
热议问题