How to use return value from method in Java?

主宰稳场 提交于 2019-12-25 18:16:27

问题


I want to use the return value from a member function by storing it into a variable and then using it. For example:

public int give_value(int x,int y) {
  int a=0,b=0,c;
  c=a+b;
  return c;
}

public int sum(int c){ 
  System.out.println("sum="+c); 
}              

public static void main(String[] args){
    obj1.give_value(5,6);
    obj2.sum(..??..);  //what to write here so that i can use value of return c 
                       //in obj2.sum
}

回答1:


try

int value = obj1.give_value(5,6);
obj2.sum(value);

or

obj2.sum(obj1.give_value(5,6));



回答2:


You give_value method returns an integer value, so you can either store that integer value in a variable like:

int returnedValueFromMethod = obj1.give_value(5,6);//assuming you created obj1
obj2.sum(returnedValueFromMethod );//passing the same to sum method on obj2 provided you have valid instance of obj2

Or if you want to compact your code (which i don't prefer), you can do it in one line like:

obj2.sum(obj1.give_value(5,6));



回答3:


This is what you need :

 public int give_value(int x,int y){
       int a=0,b=0,c;
       c=a+b;
       return c;
    }
    public int sum(int c){ 
       System.out.println("sum="+c); 
    }              
    public static void main(String[] args){
       obj2.sum(obj1.give_value(5,6));
    }


来源:https://stackoverflow.com/questions/28985402/how-to-use-return-value-from-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!