[英]How to use return value from method in Java?
我想通過將成員函數的返回值存儲到變量中然后使用它來使用它。 例如:
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
}
嘗試
int value = obj1.give_value(5,6);
obj2.sum(value);
要么
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.