如何在Java中将数组传递给方法?
您可以像普通变量一样将数组传递给方法。当我们将数组作为参数传递给方法时,实际上是将数组在内存中的地址传递(引用)。因此,方法中对此数组的任何更改都会影响该数组。
假设我们有两种方法min() 和max()接受一个数组,并且这些方法分别计算给定数组的最小值和最大值:
示例
import java.util.Scanner;
public class ArraysToMethod {
public int max(int [] array) {
int max = 0;
for(int i=0; i<array.length; i++ ) {
if(array[i]>max) {
max = array[i];
}
}
return max;
}
public int min(int [] array) {
int min = array[0];
for(int i = 0; i<array.length; i++ ) {
if(array[i]<min) {
min = array[i];
}
}
return min;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
ArraysToMethod m = new ArraysToMethod();
System.out.println("Maximum value in the array is::"+m.max(myArray));
System.out.println("Minimum value in the array is::"+m.min(myArray));
}
}输出结果
Enter the size of the array that is to be created :: 5 Enter the elements of the array :: 45 12 48 53 55 Maximum value in the array is ::55 Minimum value in the array is ::12
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短