2016-02-27 114 views
1

這是我的代碼的一小部分。事情是,不管代碼將進入那個if聲明。Java「缺少return語句」

public static double value(char[][] array, int x, int y) { 
     for (int i = 0; i < array.length; i++) { 
      for (int j = 0; j < array[0].length; j++) { 
       if (array[i][j] == (char) 120) { 
        int x_cord = i; 
        int y_cord = j; 
        int width = (x_cord - x); 
        int height = (y_cord - y); 
        Math.abs(width); 
        Math.abs(height); 
        double distance = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); 
        return distance; 
       } 

      } 
     } 
    } 

我明白,我有一個合乎邏輯的缺陷在某處,我需要以某種方式,它會到達那裏不管是什麼,但我可以做到這一點告訴程序?

+4

如果'array'是空的?在這種情況下你需要返回一些東西。或拋出異常。 – Tunaki

+0

你必須從這個方法返回。現在,只有當口譯是真實的時候你纔會回來。 –

回答

0

通過代碼有兩種可能的路徑/分支,如果您已定義您的方法返回值,則每個路徑/分支都必須具有有效的返回語句。

1

即使在運行時沒有機會到達,您在每個理論上可能的流程中都必須有return聲明。只是在結尾處加上一個「虛擬的回報,你應該罰款:

public static double value(char[][] array, int x, int y) { 
    for (int i = 0; i < array.length; i++) { 
     for (int j = 0; j < array[0].length; j++) { 
      if (array[i][j] == (char) 120) { 
       int x_cord = i; 
       int y_cord = j; 
       int width = (x_cord - x); 
       int height = (y_cord - y); 
       Math.abs(width); 
       Math.abs(height); 
       double distance = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); 
       return distance; 
      } 

     } 
    } 

    return 0; // Or some other default 
} 
+0

需要注意的是,通過使用這種模式,特殊的含義被分配給值0.在這種情況下,這可能是適當的,但它可以引入微妙的錯誤,我不覺得它是非常OO的。這就是說,鑑於手中的信息,我沒有看到任何其他解決方案。 – Gavin

1

嘗試創建一個語言環境變量double distance= 0;這樣的初始化:

public static double value(char[][] array, int x, int y) { 
    double distance= 0; 
    ... 
     return distance; 
     } 
     } 
    } 
    return distance; 
} 
2

編譯器將不接受與非的方法void返回類型,如果不是肯定會

  • 返回一個值或
  • 拋出一個異常

既然你一定總是執行循環內的return聲明,你可以添加一個return語句的任何值或拋出一個異常:

public static double value(char[][] array, int x, int y) { 
    for (int i = 0; i < array.length; i++) { 
     ... 
    } 
    throw new IllegalArgumentException("array must contain a char with code 120"); 
}