如何在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 寒露祝福语毕业寄语简短