Java程式:在向陣列輸入元素時檢查陣列邊界


陣列是一種線性資料結構,用於儲存具有相似資料型別的元素組。它以順序方式儲存資料。一旦建立了陣列,我們就無法更改其大小,即它是固定長度的。

本文將幫助您理解陣列和陣列邊界的基本概念。此外,我們將討論在向陣列輸入元素時檢查陣列邊界的Java程式。

陣列和陣列邊界

我們可以透過其索引訪問陣列的元素。假設我們有一個長度為N的陣列,那麼

從上圖可以看出,陣列中有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塊處理此錯誤。

更新於:2023年5月2日

94次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告