簡體   English   中英

如何創建一個空數組?

[英]How to create an empty array?

我是新來的,我在網上搜索過,發現它有點令人沮喪,我得到的只是在 java 數組中無法重新調整大小。 我只想弄清楚如何創建一個空數組,然后提示用戶輸入數字來填充數組? 我不想像int[] myArray = new int[5];那樣定義區域的容量int[] myArray = new int[5]; 我想定義一個空數組,用戶為其定義容量,例如-他們在數字之后輸入數字,然后輸入單詞 end 以結束程序,然后他們輸入的所有數字都將添加到空數組中,並且數量數字將是數組的容量。

您不能創建一個空數組,然后在用戶在命令行中輸入數字時讓它動態增長。 您應該讀取數字並將它們放入 ArrayList 中。 ArrayList 不需要初始大小並且會動態增長。 像這樣的東西:

public void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    BufferedReader console = 
            new BufferedReader(new InputStreamReader(System.in));
    while(true) {
        String word = console.readLine();
        if (word.equalsIgnoreCase("end") {
            break;
        } else {
            numbers.add(Integer.parseInt(word);
        }
    }

當然你不會使用while(true)並且你不會把它放在main ,但這只是為了例子

怎么樣:

Scanner scan = new Scanner(System.in);
System.out.print("Enter the array size: ");
int size = scan.nextInt();
int[] yourArray = new int[size];
//can even initialize it
Arrays.fill(yourArray, -1);

試試 ArrayList,它是一個動態數組http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

    import java.util.Scanner;


public class Ex {
public static void main(String args[]){
    System.out.println("Enter array size value");
    Scanner scanner = new Scanner(System.in);
    int size = scanner.nextInt();
    int[] myArray = new int[size];
    System.out.println("Enter array values");
    for(int i=0;i<myArray.length;i++){
        myArray[i]=scanner.nextInt();
    }
    System.out.println("Print array values");
    for(int i=0;i<myArray.length;i++){
        System.out.println("myArray"+"["+i+"]"+"="+myArray[i]);
    }
}
}

從用戶輸入中取出n並且:

int a [] = new int [n];

由於您使用的是整數,可以嘗試將ArrayList與以下示例一起使用:

ArrayList<Integer> integerListArray = new ArrayList<Integer>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM