java-java.lang.ArrayIndexOutOfBoundsException不使用数组时出错

java-java.lang.ArrayIndexOutOfBoundsException不使用数组时出错,java,Java,我正在写一个程序来显示杜威十进制信息。我还没有太多,但已经出现以下错误: 线程“main”java.lang.ArrayIndexOutOfBoundsException中出现异常异常:3 位于DDC.main(DDC.java:19) 我不明白为什么这个错误与数组有关 这是我的密码: // enter a book's catalog number and the program produces a // list of the information the catalog number

我正在写一个程序来显示杜威十进制信息。我还没有太多,但已经出现以下错误:

线程“main”java.lang.ArrayIndexOutOfBoundsException中出现异常异常:3 位于DDC.main(DDC.java:19)

我不明白为什么这个错误与数组有关

这是我的密码:

// 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

您应该确保数组的长度符合您的期望。如果依赖用户输入,最好先检查它。

您正在按空格将
catalognumber
即输入的第一行拆分为
字符串
数组

稍后,您将假设
部分
数组将有4个元素(
数组
是基于0索引的)

抛出
java.lang.ArrayIndexOutOfBoundsException
,因为您达到的索引等于或高于
数组的预期大小

如果您使用的是IDE,我建议您调试代码并在以下位置设置断点:

String topicarea = parts[0];

然后,您应该能够评估
部分
(例如,将鼠标悬停在变量上等),并找出确切的问题。

请参阅
字符串[]部分
。这个阵列有多大?您试图访问哪些位置?catalognumber的值是多少?第19行似乎是
String titleID=parts[3]。也许你在这里指的是
parts[2]
“而不是使用数组”。事实上,您正在使用一个数组。请先验证用户输入,然后检查数组的长度