![](/img/trans.png)
[英]How do I rewrite my code so that the value of 0 does not give me a out of bounds error in 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
的调用中, x
和y
值(方法调用的前两个参数)是坐标。 这些坐标必须位于您要修改的Picture
所设置的范围内:
如果Picture
的宽度为w
,则x
坐标的边界为[0 ... w - 1]
包括两端)。
如果Picture
的高度为h
,则y
坐标的边界为[0 ... h - 1]
。
“坐标超出范围”消息表示坐标(即x
和y
值)不在相应的范围内。
例如,您正在执行此操作:
int h = pic.height();
int w = pic.width();
// ...
pic.setColor(w, h, r, g, 0);
X轴的范围是0
到w - 1
,但是您要提供x
值w
。 Y轴的范围是0
到h - 1
,但是您要提供y
的h
值。 (并且在代码中的其他地方,您会犯此错误以及类似的错误。)
我不知道这意味着什么或如何解决,因此非常感谢您的帮助。
setColor
的位置,并分析您使用的x
和y
值是否在范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.