java索引越界异常_如何处理Java数组索引越界异常?

java索引越界异常_如何处理Java数组索引越界异常?通常 数组的大小固定 并且使用索引访问每个元素 例如 我们创建了一个大小为 9 的数组 然后 用于访问该数组元素的有效表达式将为 a 0 至 a 8 长度为 1 每当使用 ve 值或大于或等于数组大小的值时 都会引发 ArrayIndexOu 例如 如果执行以下代码 它将显示数组中的元素 并要求您提供索引以选择一个元素 由于数组的大小为 7 因此有效索引为 0 到 6 示例 i

通常,数组的大小固定,并且使用索引访问每个元素。例如,我们创建了一个大小为9的数组。然后,用于访问该数组元素的有效表达式将为a [0]至a [8](长度为1)。

每当使用–ve值或大于或等于数组大小的值时,都会引发ArrayIndexOutOfBoundsException。

例如,如果执行以下代码,它将显示数组中的元素,并要求您提供索引以选择一个元素。由于数组的大小为7,因此有效索引为0到6。

示例import java.util.Arrays;

import java.util.Scanner;

public class AIOBSample {

public static void main(String args[]) {

int[] myArray = {897, 56, 78, 90, 12, 123, 75};

System.out.println(“Elements in the array are:: “);

System.out.println(Arrays.toString(myArray));

Scanner sc = new Scanner(System.in);

System.out.println(“Enter the index of the required element ::”);

int element = sc.nextInt();

System.out.println(“Element in the given index is :: “+myArray[element]);

}

}

但是,如果您观察到以下输出,则我们已请求索引为9的元素,因为它是无效索引,因此引发了ArrayIndexOutOfBoundsException并终止了执行。

输出结果Elements in the array are::

[897, 56, 78, 90, 12, 123, 75]

Enter the index of the required element ::

7

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 7

at AIOBSample.main(AIOBSample.java:12)

处理异常

您可以使用try catch处理此异常,如下所示。

示例import java.util.Arrays;

import java.util.Scanner;

public class AIOBSampleHandled {

public static void main(String args[]) {

int[] myArray = {897, 56, 78, 90, 12, 123, 75};

System.out.println(“Elements in the array are:: “);

System.out.println(Arrays.toString(myArray));

Scanner sc = new Scanner(System.in);

System.out.println(“Enter the index of the required element ::”);

try {

int element = sc.nextInt();

System.out.println(“Element in the given index is :: “+myArray[element]);

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println(“The index you have entered is invalid”);

System.out.println(“Please enter an index number between 0 and 6”);

}

}

}

输出结果Elements in the array are::

[897, 56, 78, 90, 12, 123, 75]

Enter the index of the required element ::

7

The index you have entered is invalid

Please enter an index number between 0 and 6

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/209073.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 上午10:06
下一篇 2026年3月19日 上午10:06


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号