簡體   English   中英

Java字符串數組不起作用。 包含代碼

[英]Java String array not working. Code included

public static void main(String[] args) {
    int LENGTH=0;
    int currentSize=0;
    String[] albumArray = new String[LENGTH];

    Scanner sc = new Scanner(System.in);

    System.out.println("How many tracks are in your album?");
    LENGTH=sc.nextInt();
    System.out.println("Thanks.");
    System.out.println("Please enter " + LENGTH + " track names to add to the album: ");

    //Prompts user to enter values until the array is filled. Repeats until filled.
    while (currentSize < LENGTH){
        System.out.print("Enter track name "+(currentSize+1)+":\t");
        albumArray[currentSize] = sc.nextLine();
        currentSize++;
    }

    for (int i =0; i<LENGTH;i++){
        System.out.println(albumArray[i]);
        System.out.println();
    }

}

}

好的,因此基本上該程序允許用戶創建專輯。 用戶設置數組中的磁道數(LENGTH),然后將String值分配給數組中的每個索引。

在第18行下出現錯誤

"albumArray[currentSize] = sc.nextLine();"

有人知道我在做什么錯嗎? 提前致謝。

int LENGTH=0;
int currentSize=0;
String[] albumArray = new String[LENGTH]; //can't do this yet, LENGTH is still 0

Scanner sc = new Scanner(System.in);

System.out.println("How many tracks are in your album?");
LENGTH=sc.nextInt();

知道長度后,您需要創建數組。

int LENGTH=0;
int currentSize=0;

Scanner sc = new Scanner(System.in);

System.out.println("How many tracks are in your album?");
LENGTH=sc.nextInt();
String[] albumArray = new String[LENGTH];

您正在將albumArray初始化為零長度。 請在接受用戶輸入后對其進行初始化。

暫無
暫無

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

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