方法可以在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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短