如何在 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<size; 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]
广告