Java 方法
]
在Java中返回多個值
Java不支持多值返回。但是我們可以使用以下解決方案來返回多個值。
如果所有返回的元素都是相同類型的
我們可以用Java返回一個數組。下面是一個展示相同的Java程序。
// A Java program to demonstrate that a method
// can return multiple values of same type by
// returning an array
class Test
{
// Returns an array such that first element
// of array is a+b, and second element is a-b
static int[] getSumAndSub(int a, int b)
{
int[] ans = new int[2];
ans[0] = a + b;
ans[1] = a - b;
// returning array of elements
return ans;
}
// Driver method
public static void main(String[] args)
{
int[] ans = getSumAndSub(100,50);
System.out.println("Sum = " + ans[0]);
System.out.println("Sub = " + ans[1]);
}
}
上述代碼的輸出將是:
Sum = 150 Sub = 50
如果返回的元素是不同類型的
我們可以將所有返回的類型封裝到一個類中,然后返回該類的一個對象。讓我們看看下面的代碼。
// A Java program to demonstrate that we can return
// multiple values of different types by making a class
// and returning an object of class.
// A class that is used to store and return
// two members of different types
class MultiDiv
{
int mul; // To store multiplication
double div; // To store division
MultiDiv(int m, double d)
{
mul = m;
div = d;
}
}
class Test
{
static MultiDiv getMultandDiv(int a, int b)
{
// Returning multiple values of different
// types by returning an object
return new MultiDiv(a*b, (double)a/b);
}
// Driver code
public static void main(String[] args)
{
MultiDiv ans = getMultandDiv(10, 20);
System.out.println("Multiplication = " + ans.mul);
System.out.println("Division = " + ans.div);
}
}
輸出:
Multiplication = 200 Division = 0.5Java 方法
