0

我在这里有代码,它运行一系列简短的测试,以查看数组中的最后一个元素是否是预期的数字。我必须输入的代码位于 [???] 当前所在的位置。

   //The answer must be the shortest possible
class EmptyArrayException extends RuntimeException{}
class ArrayUtil{
  public static Object lastElement (Object[]array)[???]{
    if(array.length>0)return array[array.length-1];
    throw new EmptyArrayException();
  }
}
public class Exercise{
  public static void test(){
    assert ArrayUtil.lastElement(new Integer[]{1,2,3}).equals(3);
    assert ArrayUtil.lastElement(new Integer[]{1,2}).equals(2);
    assert ArrayUtil.lastElement(new Integer[]{1}).equals(1);
    assert ArrayUtil.lastElement(new Integer[]{}).equals(1);
    assert false:"Code not reachable";
  }
  public static void main(String [] arg){
    try{ test();}
    catch(Throwable t){/*the test suit
      logs t on the test results: 
      a single place for error logging.*/}
  }
}

我假设我会写 ' throws EmptyArrayException ',但这是错误的。' throws EmptyArrayException() ' 也是错误的。

那么我在 [???] 空间中放了什么?

4

1 回答 1

3

由于您的例外是 aRuntimeException您不需要指定任何内容。不过你可以。有时我这样做是为了记录这种方法可能会引发某个异常。

public static Object lastElement (Object[]array) throws EmptyArrayException 

它是由你决定。

于 2014-05-27T20:40:37.683 回答