一、通過鍵盤輸入
Java中,使用Scanner類可以方便地通過鍵盤輸入數組。具體步驟如下:
1、創建Scanner類對象。
Scanner scanner = new Scanner(System.in);
2、獲取數組長度。
int n = scanner.nextInt();
3、創建數組並輸入元素。
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
完整代碼如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// 其他操作
}
}
二、通過文件輸入
除了鍵盤輸入,Java還可以通過文件輸入數組。具體步驟如下:
1、創建Scanner類對象,並指定文件路徑。
Scanner scanner = new Scanner(new FileInputStream("input.txt"));
2、讀取文件中的數組長度。
int n = scanner.nextInt();
3、創建數組並輸入元素。
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
完整代碼如下:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream("input.txt"));
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// 其他操作
}
}
三、通過命令行參數輸入
還可以通過命令行參數輸入數組。具體步驟如下:
1、在main方法的參數列表中接收命令行參數。
public static void main(String[] args) {
// args就是命令行參數
}
2、將命令行參數解析為整型數組。
int n = Integer.parseInt(args[0]);
int[] arr = new int[n];
for (int i = 1; i < args.length; i++) {
arr[i - 1] = Integer.parseInt(args[i]);
}
完整代碼如下:
public class Main {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] arr = new int[n];
for (int i = 1; i < args.length; i++) {
arr[i - 1] = Integer.parseInt(args[i]);
}
// 其他操作
}
}
四、結語
以上介紹了Java中三種輸入數組的方法,通過鍵盤、文件和命令行參數輸入都很方便。需要根據具體情況選擇合適的輸入方式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187630.html
微信掃一掃
支付寶掃一掃