首页 > 文章列表 > Java程序在输入数组元素时检查数组边界

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

java程序 输入数组 检查边界
232 2023-09-02

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

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

数组和数组绑定

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

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

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

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

声明数组的语法

Data_Type[] nameOfarray; 
// declaration
Or,
Data_Type nameOfarray[]; 
// declaration
Or,
// declaration with size
Data_Type nameOfarray[] = new Data_Type[sizeofarray]; 
// declaration and initialization
Data_Type nameOfarray[] = {values separated with comma};

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

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

示例 1

如果我们访问数组范围内的元素,那么我们不会得到任何错误。程序将成功执行。

public class Main {
   public static void main(String []args) {
      // declaration and initialization of array ‘item[]’ with size 5
      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: " );
      // loop will iterate till 4 and will print the elements of ‘item[]’
      for(int i = 0; i <= 4; i++) {
         System.out.print(item[i] + " ");
      }
   }
}

输出

Elements of the array item: Rice Milk Bread Butter Peanut

示例 2

让我们尝试打印给定数组范围之外的值。

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 {
      // Here ‘sc’ is the object of scanner class
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter number of items: ");
      int n = sc.nextInt();
      // declaration and initialization of array ‘item[]’
      String[] item = new String[n]; 
      // try block to test the error
      try {
         // to take input from user
         for(int i =0; i<= item.length; i++) {
            item[i] = sc.nextLine();
         }
      }
      // We will handle the exception in catch block
      catch (ArrayIndexOutOfBoundsException exp) {
         // Printing this message to let user know that array bound exceeded
         System.out.println(
         " Array Bounds Exceeded  n Can't take more inputs ");
      }
   }
}

输出

Enter number of items: 3

结论

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