0
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();
    }

}

}

Okay, so basically this program allows the user to create an album. The user sets the number of tracks (LENGTH) in the array, and then assigns a String value to each index in the array.

I'm getting an error under line 18

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

Does anyone know what I'm doing wrong here? thanks in advance.

7
  • 1
    It would be better if you include what error you get Commented Apr 7, 2015 at 11:47
  • 1
    which error you are getting? Commented Apr 7, 2015 at 11:47
  • 1
    i believe one of your problem is you are creating 0 lenght array, and then you are trying to add items to it Commented Apr 7, 2015 at 11:49
  • 1
    String[] albumArray = new String[LENGTH]; put this line after taking length Commented Apr 7, 2015 at 11:49
  • Sorry. This is the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at AlbumCreatorArray.main(AlbumCreatorArray.java:18)" Commented Apr 7, 2015 at 11:49

2 Answers 2

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();

You need to create the array after you know the length.

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];
Sign up to request clarification or add additional context in comments.

Comments

0

you are initializing albumArray as zero length. Please initialize it after taking input from user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.