简体   繁体   中英

Java: getRGB() method saying index out of bounds

The intention of this code is to extract every RGB value of every pixel in turtle.jpg but for some reason it gives a index error out of bounds. Looking for some help, thanks.

int j=1;
int i=1;
BufferedImage img=null; //declares image
try {
   File sx=new File("D:/turtle.jpg");
   img = ImageIO.read(sx);
   System.out.println("Reading complete.");
}
catch(IOException e)
{
   System.out.println("Error" + e);
}
for(i=1;i<225;i++);
{
   for(j=1;j<225;j++);
   {
      deh=new Color(img.getRGB(i, j));
      int r = deh.getRed();
      int g = deh.getGreen();
      int b = deh.getBlue();
      int a = deh.getAlpha();
      System.out.print(r + " " + g + " " + b + " " + a+" ");
   }
   System.out.println();
}
/*}
catch(IOException e){
   System.out.println("error");
}*/

Hovercraft Full of Eels is absolutely right. The trouble is the scope of your loop variables! If you had done something like:

class T {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) ; {
            for (int j = 0; j < 5; j ++) ; {
               System.out.println(i + ", " + j);
            }
        }
    }
}

You would have gotten the following from the compiler:

T.java:5: error: cannot find symbol
               System.out.println(i + ", " + j);
                                  ^
  symbol:   variable i
  location: class T
T.java:5: error: cannot find symbol
               System.out.println(i + ", " + j);
                                             ^
  symbol:   variable j
  location: class T
2 errors

Lesson I relearned: it's worthwhile to reduce the scope of variables as much as possible (and no more).

A good IDE like Intellij however helps spot such errors when one is completely stumped (I know that feeling):

在此处输入图片说明 在此处输入图片说明

One definite problem in your code is here:

for(i=1;i<225;i++);    // <-- wrong semicolon!
{
   for(j=1;j<225;j++); // <-- wrong semicolon!
   {

The semicolon essentially completes the body of the for loop, hence the inner block is executed after the two loops, where i==226 and j==226 . Remove the two semicolons.

与错误的分号一起使用时,请勿对最大像素使用幻数/任意数,而应使用专用方法来获取图像的高度和宽度,否则您的代码很容易中断。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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