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();"
有谁知道我在这里做错了什么?提前谢谢。
答案 0 :(得分:5)
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];
答案 1 :(得分:0)
您正在将albumArray初始化为零长度。请在收到用户输入后进行初始化。