【问题标题】:How do I fix the "Coordinates out of bounds" error in my code in Java?如何修复 Java 代码中的“坐标越界”错误?
【发布时间】:2014-04-02 21:42:08
【问题描述】:

这是我的代码的样子。我收到一条错误消息,提示“线程“主”java.lang.arrayIndexOutofBoundsException 中的异常:坐标超出范围!” 我不知道这意味着什么或如何解决它,因此非常感谢任何帮助。

import java.awt.Color;

public class Assignment9 {

    /**
     * @param args
     * @return
     */

    public static void removeBlue(Picture pic){
        Color cPic = pic.get(100,100);
        //remove blue color pane from image, set blue weight to 0
        int h = pic.height();
        int w = pic.width();
        System.out.println(cPic);
        //^this shows the red, green, and blue weights
        int b = cPic.getBlue();
        int r = cPic.getRed();
        int g = cPic.getGreen();
        System.out.println("r=" +r +"g="+g+"b="+b);
        pic.setColor(w, h, r, g, 0);   
        for(int x=0; x<w ; x++){
                //need to set color
                pic.setColor(w, h, r, g, 0);}

    }
    public static void drawredStripe(Picture pic){
    //draw a red vertical stripe that is 200 pixels wide through the middle of the image
        Color cPic = pic.get(100,100);
        int h = pic.height();
        int w = pic.width();
        int b = cPic.getBlue();
        int r = cPic.getRed();
        int g = cPic.getGreen();
        for(int x=0; x<h ; x++){
            for (int y = (w/2)-100; y <(w/2)+100; y++){
                //need to set color
                pic.setColor(x, y, r, 0, 0);
            }
        }

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Picture dolphin= new Picture("dolphin_swimming.jpg");
        removeBlue(dolphin);   
        dolphin.show();
        drawredStripe(dolphin);
        dolphin.show(); 
}
}

【问题讨论】:

  • 错误来自哪一行?还有什么是w?如果 w
  • drawredstripe 中,您使用x 作为垂直坐标,y 作为水平坐标。这对我来说似乎不对。

标签: java coordinates bounds


【解决方案1】:

我猜是

pic.setColor(w, h, r, g, 0);

您正在迭代 x,但没有在 removeBlue 的 for 循环中使用 x。

坐标 (w,h) 可能超出错误所声称的范围

【讨论】:

    【解决方案2】:

    在您对setColor 的调用中,xy 值(方法调用的前两个参数)是坐标。并且这些坐标必须在您尝试修改的Picture 设置的范围内:

    • 如果Picture 的宽度为w,则x 坐标的边界为[0 ... w - 1](含)。

    • 如果Picture 的高度为h,则y 坐标的边界为[0 ... h - 1](含)。

    “坐标超出范围”消息表示坐标(即xy 值)不在各自的范围内。

    例如你正在这样做:

        int h = pic.height();
        int w = pic.width();
        // ...
        pic.setColor(w, h, r, g, 0);
    

    X 轴上的界限是0w - 1,但您提供的x 值是w。 Y 轴上的界限是0h - 1,但您提供的y 值是h。 (并且在您的代码中还有其他地方您会犯此错误和类似错误。)


    我不知道这意味着什么或如何解决它,因此非常感谢任何帮助。

    1. 阅读并理解上述说明。
    2. 查看您调用setColor 的位置并分析您使用的xy 值是否在界限内。
    3. 如有必要,更改代码。
    4. 测试...并根据需要重复前面的步骤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多