blynchus
blynchus

Reputation: 1

java - java.lang.ArrayIndexOutOfBoundsException error while not using an array

I am writing a program to display Dewey Decimal Information. I don't have much yet, but am already getting the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at DDC.main(DDC.java:19)

I don't understand why the error is array related

here's my code:

// enter a book's catalog number and the program produces a
// list of the information the catalog number provides for the user

import java.util.Scanner;

public class DDC {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a catalog number
        System.out.println("Enter the catalog number: ");
        String catalognumber = input.nextLine();
        int strLength = catalognumber.length();

        if (strLength == 15) {
            String[] parts = catalognumber.split(" ");
            String topicarea = parts[0];
            String authorID = parts[1];
            String titleID = parts[3];
            System.out.println("This is a Dewey Decimal Classification(DDC) for Non-fiction");
            System.out.println("Topic Area: "+ topicarea);
            System.out.println("Author Identifier: "+ authorID);
            System.out.println("Title Identifier: " + titleID);
            System.out.println("Thanks for using the Catalog Information Program.");

        } // end if

    } // end main

} // end DDC

Upvotes: 0

Views: 83

Answers (2)

Mena
Mena

Reputation: 48404

You are splitting catalognumber, that is, the first line of your input, into a String array, by spaces.

You are later assuming that your parts array will have 4 elements (arrays are 0-index-based).

The java.lang.ArrayIndexOutOfBoundsException is thrown because you are reaching an index equal or higher than the expected size of your array.

If you're using an IDE, I suggest you debug your code and set a breakpoint at:

String topicarea = parts[0];

You should by then be able to evaluate parts (e.g. by hovering over the variable, etc.) and figure out the precise issue.

Upvotes: 1

Dragos Giurca
Dragos Giurca

Reputation: 16

You should make sure that the length of your array matches your expectations. It is a good practice to check it before if you rely on user input.

Upvotes: 0

Related Questions