如果一段代码处理结果产生了多个变量,我将这段代码写成单独的一个方法后如何返回值
时间: 2024-05-06 16:21:10 浏览: 10
可以通过在方法定义时使用一个数组或一个对象来返回多个变量的值。例如,使用一个数组来返回多个整数变量的值:
```java
public static int[] calculate(int x, int y) {
int result1 = x + y;
int result2 = x - y;
int[] results = {result1, result2};
return results;
}
```
在调用该方法时,可以通过数组下标来获取不同的结果:
```java
int[] results = calculate(10, 5);
int sum = results[0];
int difference = results[1];
```
类似地,你也可以使用一个对象(例如一个自定义的类)来返回多个变量的值,例如:
```java
public class CalculationResult {
public int sum;
public int difference;
}
public static CalculationResult calculate(int x, int y) {
int result1 = x + y;
int result2 = x - y;
CalculationResult result = new CalculationResult();
result.sum = result1;
result.difference = result2;
return result;
}
```
在调用该方法时,可以通过对象的属性来获取不同的结果:
```java
CalculationResult result = calculate(10, 5);
int sum = result.sum;
int difference = result.difference;
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)