如何在 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP