Reputation:
Say I have a java function as follows,
public static int my(int a, int b)
{
int c = a + b;
return c;
String d = "Some Data";
return d;
float f = a/b;
return f
}
So, how do I get the 3 return values separately?
all the values are of different data types.
I've seen this question and this question but couldn't understand properly.
Upvotes: 0
Views: 177
Reputation: 1583
public class DataStorage{
private int a;
private String data;
private float f;
public DataStorage(int a, String data, float f){
this.a = a;
this.data = data;
this.f = f;
}
/* standard get/set method. */
}
public static DataStorage my(int a, int b)
{
int c = a + b;
String d = "Some Data";
float f = a/b;
DataStorage dataStorage = new DataStorage(c,d,f);
return dataStorage;
}
Upvotes: 0
Reputation: 2208
return array of int.. e.g. int[]...
public static int[] my(int a, int b) {
int res[] = new int[4];
int c = a + b;
res[0] = c;
int d = a * b;
res[1] = d;
int e = a - b;
res[2] = e;
int f = a / b;
res[3] = f;
return res;
}
Upvotes: 1
Reputation: 213
any function can only return one value. What you can do is to create an objet containing all your answers and return this object.
class ResultObject
{
public int c;
public int d;
public int e;
public int f;
}
in your function white
public static ResultObject my(int a, int b)
{
ResultObject resObject = new ResultObject();
resObject.c = a + b;
resObject.d = a*b;
resObject.e = a-b;
resObject.f = a/b;
return resObject;
}
You can return only one value. You have to make that value to "contain" other values.
Upvotes: 4
Reputation: 8947
There are two ways.
Reason for this is that Java is a strongly-typed programming language. Wanna describe a new data structure - write a new class.
Upvotes: 1
Reputation: 2081
You can return only one element but the element may be array or list.you may return list of values.(some exercise). I hope this may bring some solution.
Upvotes: 0
Reputation: 35587
You can try something like this
public static int[] my(int a, int b) { // use an array to store values
int[] arr = new int[4];
int c = a + b;
arr[0] = c;
int d = a * b;
arr[1] = d;
int e = a - b;
arr[2] = e;
int f = a / b;
arr[3] = f;
return arr; // return values
}
Upvotes: 0