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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28985402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:08:29  来源:igfitidea点击:

How to use return value from method in Java?

javaclassobjectreturnmember

提问by Amit Tegwan

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
}

回答by Thomas Stets

try

尝试

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

or

或者

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

回答by SMA

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

Yougive_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

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

回答by Gnanadurai A

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