Java 中的方法能返回多个值吗?
在 Java 中,你只能返回单个值。如有需要,可以使用数组或对象返回多个值。
示例
在以下给出的示例中,calculate() 方法接受两个整型变量,对它们执行加法、减法、乘法和除法运算,并将结果存储在数组中并返回该数组。
public class ReturningMultipleValues {
static int[] calculate(int a, int b){
int[] result = new int[4];
result[0] = a + b;
result[1] = a - b;
result[2] = a * b;
result[3] = a / b;
return result;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
int[] result = calculate(a, b);
System.out.println("Result of addition: "+result[0]);
System.out.println("Result of subtraction: "+result[1]);
System.out.println("Result of multiplication: "+result[2]);
System.out.println("Result of division: "+result[3]);
}
}
输出
Enter the value of a: 20 Enter the value of b: 10 Result of addition: 30 Result of subtraction: 10 Result of multiplication: 200 Result of division: 2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP