溫馨提示×

java如何創(chuàng)建順序表并輸入數(shù)據(jù)

小億
97
2024-01-13 10:26:15
欄目: 編程語言

在Java中,可以使用數(shù)組來實現(xiàn)順序表,并通過用戶輸入來填充數(shù)據(jù)。以下是一個示例代碼:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 獲取順序表的長度
        System.out.print("請輸入順序表的長度:");
        int size = scanner.nextInt();
        
        // 創(chuàng)建順序表的數(shù)組
        int[] list = new int[size];
        
        // 輸入數(shù)據(jù)
        System.out.println("請輸入順序表的數(shù)據(jù):");
        for (int i = 0; i < size; i++) {
            list[i] = scanner.nextInt();
        }
        
        // 打印順序表
        System.out.println("順序表的數(shù)據(jù)為:");
        for (int i = 0; i < size; i++) {
            System.out.print(list[i] + " ");
        }
    }
}

運行程序后,首先輸入順序表的長度,然后逐個輸入數(shù)據(jù)。最后,程序會打印出輸入的順序表數(shù)據(jù)。

注意:該示例程序假設(shè)用戶輸入的都是整數(shù),如果需要處理其他類型的數(shù)據(jù),需要相應(yīng)地修改代碼。

0