我们可以从Java中的方法返回Java中的数组。在这里,我们有一个createArray()方法,通过从用户那里获取值来动态创建一个数组并返回创建的数组。
示例import java.util.Arrays;
import java.util.Scanner;
public class ReturningAnArray {
public int[] createArray() {
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
myArray[i] = sc.nextInt();
}
return myArray;
}
public static void main(String args[]) {
ReturningAnArray obj = new ReturningAnArray();
int arr[] = obj.createArray();
System.out.println("Array created is :: "+Arrays.toString(arr));
}
}
输出结果Enter the size of the array that is to be created::
5
Enter the elements of the array ::
23
47
46
58
10
Array created is :: [23, 47, 46, 58, 10]