首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 數組越界與空指針異常深度解析:for 循環中動態創建數組的陷阱

     編輯:程式設計疑難解答

問題代碼對比

案例一:數組下標越界

public class Test {
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            Scanner in = new Scanner(System.in);
            System.out.println("請輸入成績");
            int[] a = new int[i]; // 💥 關鍵錯誤:i=0 時創建長度為 0 的數組
            a[i] = in.nextInt();  // 訪問 a[0] 拋出 ArrayIndexOutOfBoundsException
            System.out.println("成績是" + a[i]);
        }
    }
}

案例二:空指針異常

public class BlackDemo {
    static int[] b; // 類變量,默認值為 null
    
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            Scanner in = new Scanner(System.in);
            System.out.println("請輸入成績");
            b[i] = in.nextInt(); // 💥 b 為 null,拋出 NullPointerException
            System.out.println("成績是" + b[i]);
        }
    }
}

錯誤根因圖解

循環輪次i 值案例一:new int[i]案例二:static int[] b
第 1 次0創建長度 0 的數組 → a[0] 越界b 為 null → b[0] 空指針
第 2 次1創建長度 1 的數組 → a[1] 越界b 仍為 null → 空指針

核心知識點

1. 數組創建時長度必須為常量或確定的正整數

// ❌ 錯誤:長度隨循環變量變化,首次為 0
int[] a = new int[i];

// ✅ 正確:在循環外預先分配固定大小
int[] a = new int[2]; // 或根據實際需求確定大小
for (int i = 0; i < a.length; i++) {
    a[i] = in.nextInt();
}

2. 靜態數組變量默認值為 null,必須显式初始化


// ❌ 錯誤:僅聲明未初始化
static int[] b;

// ✅ 正確:聲明時初始化或在使用前初始化
static int[] b = new int[2]; // 指定長度
// 或
static int[] b = {0, 0}; // 直接初始化

3. 動態收集輸入建議使用集合

List<Integer> scores = new ArrayList<>();
for (int i = 0; i < 2; i++) {
    scores.add(in.nextInt());
}
// 如需轉數組
int[] arr = scores.stream().mapToInt(Integer::intValue).toArray();

調試技巧

  1. 打印數組長度:System.out.println("數組長度: " + a.length);
  2. 打印引用地址:System.out.println("b 引用: " + b);(null 顯示為 null)
  3. 使用 IDE 斷點調試,觀察變量變化

總結

  • ArrayIndexOutOfBoundsException:訪問索引 ≥ 數組長度 或 < 0
  • NullPointerException:對 null 引用進行解引用(訪問成員/索引)
  • **預防核心**:數組使用前必須 new 固定長度 或 初始化,循環內動態創建極易出錯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved