Javaでキーボードから配列を入力する方法【初心者向け】

Javaでは、Scannerクラスを使用してキーボードから配列を入力することができます。以下はサンプルコードです:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();
        
        int[] arr = new int[size];
        
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < size; i++) {
            arr[i] = scanner.nextInt();
        }
        
        System.out.println("The input array is:");
        for (int i = 0; i < size; i++) {
            System.out.print(arr[i] + " ");
        }
        
        scanner.close();
    }
}

上記のコードでは、まずScannerクラスを使用してキーボードから配列のサイズを入力し、その後サイズが整数の配列を作成します。そして、ループを使ってキーボードから配列の要素を入力し、入力された配列を出力します。最後にScannerオブジェクトを閉じます。

bannerAds