|
-
Jan 24th, 2002, 05:15 PM
#1
Return many variable in a Function
How can I return more than one variable with a function with Java?
-
Jan 24th, 2002, 05:22 PM
#2
Member
You can't, sort of. But in Java nearly all classes are not immutable. So you can do this trick except with primatives (int, long, byte, etc.) and the String class.
Code:
public void doCrap(StringBuffer s1, StringBuffer s2)
{
s1.append(s2);
s2.doOtherCrap();
}
-
Jan 24th, 2002, 05:50 PM
#3
Or you can have a class that will expose some members/methods and then return an object from your method.
-
Jan 24th, 2002, 06:42 PM
#4
Here is an example can you just change it ... I do not understand what both you mean.
Code:
public class returnClass {
public static void main ( String Args[])
{
int iPrice1,iPrice2;
iPrice1 = 100;
iPrice2 = 13;
System.out.println("Price 1 : " + iPrice1 + "\nPrice 2 : " + iPrice2);
}
public static int SwitchNumbers(int iX, int iY)
{
int itempo=0;
iTempo = iX;
iX=iY;
iY=itempo;
return iX,iY;
}
}
-
Jan 25th, 2002, 06:40 PM
#5
-
Jan 25th, 2002, 06:46 PM
#6
Member
Eh, I just said you can't do that technique with non-immutable data types which include primitives. I don't have a clear understanding of what Serge is talking about, too.
-
Jan 25th, 2002, 08:22 PM
#7
Maybe something like this:
Code:
public class RetClass
{
private int val1;
private int val2;
public RetClass()
{
val1 = 0;
val2 = 0;
}
public RetClass(int a, int b)
{
val1 = a;
val2 = b;
}
public int getVal1()
{
return val1;
}
public int getVal2()
{
return val2;
}
}
then just use this class in your main class
Code:
import RetClass;
class MyClass
{
public static void main(String args[])
{
RetClass ret = DoCrap(5, 6);
System.out.println("Returned values are a: " + ret.getVal1() + " b: " + ret.getVal2());
}
public static RetClass DoCrap(int a, int b)
{
//here do something with your a and b values
a = (a * b);
b = b * 2;
RetClass ret = new RetClass(a, b);
return ret;
}
}
-
Jan 28th, 2002, 06:30 AM
#8
Thx you
-
Jan 31st, 2002, 04:53 PM
#9
New Member
Or, I suppose that you could create an array or Vector with the info that you would like to return and then return the array or the Vector.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|