繁体   English   中英

如何在Java代码中修复“坐标超出范围”错误?

[英]How do I fix the “Coordinates out of bounds” error in my code in Java?

这是我的代码的样子。 我收到一条错误消息,指出“线程“ main”中的异常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(); 
}
}

我猜是

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

您正在遍历x,但没有在removeBlue的for循环中不使用x。

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

在对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 ,但是您要提供xw Y轴的范围是0h - 1 ,但是您要提供yh值。 (并且在代码中的其他地方,您会犯此错误以及类似的错误。)


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM