【问题标题】:How to use return value from method in Java?如何在 Java 中使用方法的返回值?
【发布时间】:2015-05-13 04:05:58
【问题描述】:

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

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
}

【问题讨论】:

  • 你用谷歌搜索过/关注过教程吗?
  • 您的 sum 方法应声明为 public void sum(int c),因为您不会从中返回值。

标签: java class object return member


【解决方案1】:

试试

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这是你需要的:

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

      【讨论】:

        猜你喜欢
        • 2023-01-07
        • 2021-09-04
        • 2013-10-15
        • 1970-01-01
        • 2015-01-20
        • 2011-11-28
        • 2016-01-25
        • 1970-01-01
        • 2014-02-28
        相关资源
        最近更新 更多