簡體   English   中英

Java:getRGB()方法說索引超出范圍

[英]Java: getRGB() method saying index out of bounds

這段代碼的目的是提取turtle.jpg中每個像素的每個RGB值,但是由於某種原因,它會給索引帶來超出范圍的錯誤。 尋求幫助,謝謝。

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");
}*/

充滿鰻魚的氣墊船是絕對正確的。 麻煩的是您的循環變量的范圍! 如果您做了類似的事情:

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);
            }
        }
    }
}

您將從編譯器中獲得以下內容:

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

我吸取的教訓是:盡可能減少變量的范圍(而不是更多)是值得的。

但是,像Intellij這樣的優秀IDE可以在一個人完全陷入困境時幫助發現此類錯誤(我知道那種感覺):

在此處輸入圖片說明 在此處輸入圖片說明

您的代碼中有一個確定的問題是:

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

分號基本上完成了for循環的主體,因此內部塊在兩個循環之后執行,其中i==226j==226 刪除兩個分號。

與錯誤的分號一起使用時,請勿對最大像素使用幻數/任意數,而應使用專用方法來獲取圖像的高度和寬度,否則您的代碼很容易中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM