You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何可打印数组索引元素,初始化变量时却抛出ArrayIndexOutOfBoundsException?

Fixing ArrayIndexOutOfBoundsException When Parsing File Input in Java

Let's break down why you're hitting this error and how to fix it step by step.

What's Causing the Issue?

From your output, we can see the first line of your file (2 3 0 8) is parsed and printed correctly, but the exception fires right after. Here are the two most likely reasons:

  1. Insufficient Lines in Your File
    You told the program to solve 3 linear equations, but it looks like file.txt only has one valid line of data. When the loop runs the second time, sc.nextLine() reads an empty line (or hits the end of the file), splitting that empty string gives an array with fewer than 4 elements. Trying to access lineArr[1] here triggers the out-of-bounds exception.

  2. Unconsumed Newline in Input Buffer
    After using keyboard.next() to grab the filename, the newline character you pressed to submit the name stays in the input buffer. The first sc.nextLine() might read this empty newline instead of the first line of your file. While your output shows a valid line was read, this could still cause issues if your file has exactly 3 lines (the first read would be empty, leading to an immediate exception).

How to Fix It

Here are actionable fixes to resolve the problem:

1. Verify Your File Content

Make sure file.txt has exactly 3 lines, each with 4 space-separated numbers (matching the number of equations you specified). Example valid content:

2 3 0 8
1 -1 1 2
4 0 -3 1

2. Clean Up the Input Buffer

After reading the filename with keyboard.next(), add a keyboard.nextLine() to consume the leftover newline character:

System.out.println("Enter file name: ");
String fileName = keyboard.next();
keyboard.nextLine(); // Clear the remaining newline from input
Scanner sc = new Scanner(new FileReader(fileName));

3. Add Boundary Checks & Robust Splitting

Before accessing elements in lineArr, check if it has at least 4 elements to avoid exceptions. Also, use split("\\s+") instead of split(" ") to handle multiple spaces/tabs between numbers:

String line = sc.nextLine().trim(); // Trim whitespace to skip empty lines
String[] lineArr = line.split("\\s+"); // Split on any whitespace

// Validate the line has enough values
if (lineArr.length < 4) {
    sc.close();
    throw new IllegalArgumentException("Invalid line: " + line + " — expected 4 numbers.");
}

// Now safely parse the values
x = parseDouble(lineArr[0]);
y = parseDouble(lineArr[1]);
z = parseDouble(lineArr[2]);
b = parseDouble(lineArr[3]);

Modified Full Code Snippet

Here's your updated code with all fixes applied:

else { 
    System.out.println("Enter file name: "); 
    String fileName = keyboard.next(); 
    keyboard.nextLine(); // Consume leftover newline
    Scanner sc = new Scanner(new FileReader(fileName)); 
    double x,y,z,b; 
    for (int i = 0; i < numLinEq; i++) { 
        String line = sc.nextLine().trim(); 
        String[] lineArr = line.split("\\s+"); 
        
        // Debug print of elements
        for(int j=0;j< lineArr.length;j++){ 
            System.out.println(lineArr[j]); 
        } 
        
        // Validate line format
        if (lineArr.length < 4) {
            sc.close();
            throw new IllegalArgumentException("Line " + (i+1) + " has missing values: " + line);
        }
        
        x=parseDouble(lineArr[0]); 
        y=parseDouble(lineArr[1]); 
        z=parseDouble(lineArr[2]); 
        b=parseDouble(lineArr[3]); 
        xyzArr[i][0] = x; 
        xyzArr[i][1] = y; 
        xyzArr[i][2] = z; 
        bArr[i] = b; 
    } 
    sc.close(); // Clean up the scanner
    double[] answerArr = gaussianElimSolve(xyzArr, bArr); 
    System.out.println("x = " + Math.round(answerArr[0]) + "\ny = " + Math.round(answerArr[1]) + "\nz = " + Math.round(answerArr[2])); 
} 

private static double parseDouble(String str) { 
    if (str == null || str.isEmpty()) { 
        return 0.0; 
    } else { 
        return Double.parseDouble(str); 
    } 
}

These changes should eliminate the ArrayIndexOutOfBoundsException and make your code more resilient to invalid input.

内容的提问来源于stack exchange,提问作者D.Park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:22:58