如何在 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