Java 程序在将元素输入数组时检查数组边界

javaobject oriented programmingprogramming

数组是一种线性数据结构,用于存储具有相似数据类型的元素组。它以顺序方式存储数据。一旦我们创建了一个数组,我们就不能改变它的大小,即它的长度是固定的。

本文将帮助您理解数组和数组边界的基本概念。此外,我们将讨论 Java 程序在将元素输入数组时检查数组边界。

数组和数组边界

我们可以通过数组的索引访问数组元素。假设我们有一个长度为 N 的数组,那么

我们可以在上图中看到数组中有 7 个元素,但索引值从 0 到 6,即 0 到 7 - 1。

数组的范围称为其边界。上述数组的范围是从 0 到 6,因此,我们也可以说 0 到 6 是给定数组的边界。如果我们尝试访问超出其范围或负索引的索引值,那么我们将得到 ArrayIndexOutOfBoundsException。这是在运行时发生的错误。

声明数组的语法

Data_Type[] nameOfarray;
// 声明
或者,
Data_Type nameOfarray[];
// 声明
或者,
// 带大小的声明
Data_Type nameOfarray[] = new Data_Type[sizeofarray];
// 声明和初始化
Data_Type nameOfarray[] = {用逗号分隔的值};

我们可以在程序中使用上述任何语法。

在将元素输入数组时检查数组边界

示例 1

如果我们在数组边界内访问数组元素,则不会出现任何错误。程序将成功执行。

public class Main {
   public static void main(String []args) {
      // 声明并初始化大小为 5 的数组'item[]'
      String[] item = new String[5]; 
      // 0 to 4 is the indices 
      item[0] = "Rice";
      item[1] = "Milk";
      item[2] = "Bread";
      item[3] = "Butter";
      item[4] = "Peanut";
      System.out.print(" Elements of the array item: " );
      // 循环将迭代到 4 并打印"item[]"的元素
      for(int i = 0; i <= 4; i++) {
         System.out.print(item[i] + " ");
      }
   }
}

输出

Elements of the array item: Rice Milk Bread Butter Peanut

示例 2

Let's try to print the value outside the range of the given array.

public class Tutorialspoint {
      public static void main(String []args) {
      String[] item = new String[5];
      item[0] = "Rice";
      item[1] = "Milk";
      item[2] = "Bread";
      item[3] = "Butter";
      item[4] = "Peanut";
      // trying to run the for loop till index 5
      for(int i = 0; i <= 5; i++) {
         System.out.println(item[i]);
      }
   }
}

输出

Rice
Milk
Bread
Butter
Peanut
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Tutorialspoint.main(Tutorialspoint.java:11)

正如我们之前所讨论的,如果我们尝试访问超出其范围或负索引的数组的索引值,则将获得 ArrayIndexOutOfBoundsException。

在上面的程序中,我们尝试执行 for 循环直到数组"item[]"的索引 5,但其范围仅为 0 到 4。因此,在打印元素到 4 之后,我们收到错误。

示例 3

在此示例中,我们尝试使用 try 和 catch 块处理 ArrayIndexOutOfBoundsException。我们将在用户将元素输入数组时检查数组边界。

import java.util.*;
public class Tutorialspoint {
   public static void main(String []args) throws ArrayIndexOutOfBoundsException {
      // 这里的 'sc' 是扫描仪类的对象
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter number of items: ");
      int n = sc.nextInt();
      // 声明并初始化数组'item[]'
      String[] item = new String[n]; 
      // try block to test the error
      try {
         // 获取用户输入
         for(int i =0; i<= item.length; i++) {
            item[i] = sc.nextLine();
         }
      }
      // 我们将在 catch 块中处理异常
      catch (ArrayIndexOutOfBoundsException exp) {
         // 打印此消息以让用户知道超出数组界限
         System.out.println(
         " Array Bounds Exceeded  \n Can't take more inputs ");
      }
   }
}

输出

Enter number of items: 3

结论

在本文中,我们了解了数组和数组绑定。我们讨论了为什么如果我们尝试访问数组范围之外的元素会出错,以及如何使用 try 和 catch 块处理此错误。


相关文章