如何在Java中使用方法返回值?

如何在Java中使用方法返回值?,java,class,object,return,member,Java,Class,Object,Return,Member,我想通过将成员函数的返回值存储到变量中,然后使用它来使用它。例如: 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)

我想通过将成员函数的返回值存储到变量中,然后使用它来使用它。例如:

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
}
试一试

试一试


give_value
方法返回一个整数值,因此您可以将该整数值存储在变量中,如:

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
或者,如果您想压缩代码(我不喜欢),可以在一行中完成,如下所示:

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

give_value
方法返回一个整数值,因此您可以将该整数值存储在变量中,如:

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
或者,如果您想压缩代码(我不喜欢),可以在一行中完成,如下所示:

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

这就是您需要的:

 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));
    }

这就是您需要的:

 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));
    }

你用谷歌搜索过/遵循过教程吗?你的
sum
方法应该声明为
public void sum(int c)
,因为你没有从中返回值。你用谷歌搜索过/遵循过教程吗?你的
sum
方法应该声明为
public void sum(int c)
,因为你没有从中返回值。