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

图像垂直翻转实现求助:Java代码运行报错(Main.java:403)

Fixing Your Vertical Image Flip Java Code (Array Index Out of Bounds Error)

Let's break down why you're hitting that error at img[row][col] = img[height - row - 1][col] and fix it step by step. The core issue here is a mix-up in how you're calculating the image's height and width, which is causing an array index out of bounds exception.

What's Wrong in Your Current Code

  1. Swapped height and width definitions
    When storing an image as a 2D array int[][] img, the structure follows img[row][column]. That means:

    • The height of the image is the number of rows: img.length
    • The width is the number of columns per row: img[0].length
      Your code has these reversed (height = img[0].length, width = img.length). So when you loop using height/2 as the row limit and access img[height - row -1][col], you're trying to access a row index that doesn't exist (since height here is actually the width/column count). That's exactly what's throwing the error.
  2. Unintentional parameter override
    You're passing img as a method parameter but immediately overwriting it with Util.readImageToMatrix(dir). This makes the input parameter useless—either remove the parameter or move the image reading logic outside the method.

Corrected Code

Here's the fixed version with clear improvements:

public static int[][] flipVertically() {
    // Read the image once at the start of the method
    String dir = "image.jpg";
    int[][] img = Util.readImageToMatrix(dir);
    
    // Correct height and width calculations
    int height = img.length;
    int width = img[0].length;
    
    // Swap top rows with corresponding bottom rows (only need to loop through half the rows)
    for(int row = 0; row < height / 2; row++) {
        for(int col = 0; col < width; col++) {
            // Store the top pixel temporarily
            int tempPixel = img[row][col];
            // Assign bottom pixel to top position
            img[row][col] = img[height - row - 1][col];
            // Assign stored top pixel to bottom position
            img[height - row - 1][col] = tempPixel;
        }
    }
    return img;
}

Key Fixes Explained

  • Corrected dimension logic: Now height properly refers to the number of rows, so height - row -1 will always point to a valid row index from the bottom half of the image.
  • Cleaned up method structure: I removed the redundant img parameter since you're reading the image inside the method. If you intended to pass a pre-existing matrix instead, just add the parameter back and remove the Util.readImageToMatrix line inside the method.

This should resolve the index out of bounds error you're seeing, and the vertical flip will work as expected.

内容的提问来源于stack exchange,提问作者Slurp123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:46:53