如何从Java中的方法返回数组?
我们可以从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]
热门推荐
10 天气转凉祝福语简短
11 车行销售祝福语简短
12 打牌翻盘祝福语简短
13 祖国七十华诞简短祝福语
14 结婚对白誓言简短祝福语
15 朋友花篮开业祝福语简短
16 形容新年的祝福语简短
17 少先队代表送祝福语简短
18 周一情人祝福语简短