如何在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 夏日升学宴祝福语简短