2012-02-16 44 views
3
boolean openingboard; 
{ 
Robot robot = new Robot(); 
Color color3 = new Color(108, 25, 85); 
Rectangle rectangle = new Rectangle(0, 0, 1365, 770); 
    while(true) 
    { 
    BufferedImage image = robot.createScreenCapture(rectangle); 
    search: for(int x = 0; x < rectangle.getWidth(); x++) 
     { 
     for(int y = 0; y < rectangle.getHeight(); y++) 
      { 
       if(image.getRGB(x, y) == color3.getRGB()) 
       { 
        System.out.println("About to finish and return true"); 
        return true; 
       } 
       System.out.println("About to finish and return false"); 
      } 
     } 
    } 
} 

的錯誤是: 的java:71:回到外面方法返回外面方法錯誤

還真

^

我不知道這是什麼情況發生,請幫助!

+1

所有這些代碼裏面的方法嗎? – 2012-02-16 02:27:35

+0

裏面的方法開幕?是不是主要的方法,但我應該張貼? – user1179522 2012-02-16 02:29:51

回答

7

從上面您的評論的反應,我要做出猜測,你認爲

boolean openingboard; 
{ 
    return true; 
} 

定義了一個名爲openingboard Java方法。情況並非如此。 Java遵循C範式,要求您​​在括號中指定參數,而不管您是否有任何參數。因此,該方法

boolean openingboard() { 
    return true; 
} 

是一個有效的Java方法(假設它是一些類中),如同在大括號之間太多的代碼版本的openingboard

這就是說,我要沿着Java的風格幾友好指針傳遞:

  • 的Java(實際上大多數高級語言),程序員往往不贊成「永遠」循環,例如while (true) ,因爲這些循環使得確定循環實際停止的難度更大。
  • 代碼中不需要標籤search,標籤甚至比永久環路更令人沮喪。

所以,我建議重寫你的代碼看起來像

private boolean openingboard() { 
    Robot robot = new Robot(); 
    Color color3 = new Color(108, 25, 85); 
    Rectangle rect = new Rectangle(0, 0, 1365, 770); 
    BufferedImage image = robot.createScreenCapture(rect); 
    for(int x = 0; x < rectangle.getWidth(); x++) { 
     for(int y = 0; y < rectangle.getHeight(); y++) { 
      if(image.getRGB(x, y) == color3.getRGB()) 
       return true; 
     } 
    } 

    return false; 
} 

假設,當然,你更喜歡一個調試器來跟蹤打印。

+0

關於標籤,我還沒有聽到很多評論 - 積極或消極 - 。我會認爲他們是良性的。那麼他們爲什麼皺起眉頭呢? – emory 2012-02-16 17:09:43

+0

@emory除非您將標籤用於嵌套中斷或繼續,否則評論沒有提供的標籤絕對沒有價值。因此,評論更符合公約。對於嵌套的break/continue語句,標籤是可以的,但對於任何其他原因不需要。我將使用C goto對Java標籤進行分類:在非常有限的情況下提高可讀性很有用,但不要在該集合之外使用它。 – 2012-02-16 22:27:13

+0

@emory使用標籤幾乎與goto語句[認爲有害]是一回事(https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF)。 – ThomasW 2016-06-13 07:15:15

4

正確的方法是這樣的:boolean openingboard ()

不喜歡boolean openingboard;

括號是不可選的。

你擁有它的方式:開放板是一個領域。有一個帶有Robot和一個顏色的init塊,以及一些嵌套在一起的循環。在for循環中的一個內部是init塊中不允許的返回。