gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:13:32 25 4
gpt4 key购买 nike

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

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at 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(即输入的第一行)按空格拆分为String 数组。

您稍后假设您的 parts 数组将有 4 个元素(array 基于 0 索引)。

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

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

String topicarea = parts[0];

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

关于java - 不使用数组时出现 java.lang.ArrayIndexOutOfBoundsException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com