2016-11-12 112 views
-1

當我嘗試編譯此代碼時,出現以下錯誤,該代碼應該創建不使用泛型的自定義Java數組。我很確定這是不正確創建陣列,但我不確定。如何調用自定義Java數組

任何幫助將非常感謝!謝謝!

當前編譯錯誤摘錄:

51: error: unreported exception Exception; must be caught or declared to be thrown strList.add("str1"); 

自定義數組類:

public class MyList { 

Object[] data; // list itself. null values at the end 
int capacity; // maximum capacity of the list 
int num; // current size of the list 
static final int DEFAULT_CAPACITY = 100; 

public MyList() { 
    this(DEFAULT_CAPACITY); // call MyList(capacity). 
} 
public MyList(int capacity) { 
    this.capacity = capacity; 
    data = new Object[capacity]; // null array 
    num = 0; 
} 
public void add(Object a) throws Exception { 
    if (num == capacity) { 
     throw new Exception("list capacity exceeded"); 
    } 
    data[num] = a; 
    num++; 
} 
public Object get(int index) { 
    // find the element at given index 
    if (index < 0 || index >= num) { 
     throw new RuntimeException("index out of bounds"); 
    } 
    return data[index]; 
} 
public void deleteLastElement() { 
    // delete the last element from the list 
    // fill in the code in the class. 
    if (num == 0) { 
     throw new RuntimeException("list is empty: cannot delete"); 
    } 
    num--; 
    data[num] = null; 
} 
public void deleteFirstElement() { 
    // delete first element from the list 
    for (int i = 0; i < num - 1; i++) { 
     data[i] = data[i + 1]; 
    } 
    data[num - 1] = null; 
    num--; // IMPORTANT. Re-establish invariant 
} 


public static void main(String[] args) { 
    MyList strList = new MyList(); 
    strList.add("str1"); 
    strList.add("str2"); 
    System.out.println("after adding elements size =" + strList); 
} 


} 
+0

如果答案被接受,你應該將其標記爲這樣...(下答案得分V符號) – ItamarG3

回答

0

您需要聲明main這樣做,這將引發CAN例外:

public static void main(String[] args) throws Exception{ 
... 

strList.add(...)try-catch塊:

... 
try{ 
    strList.add("str1"); 
    strList.add("str2"); 
} catch(Exception e){ 
    e.printStackTrace(); 
} 
+1

你永遠需要聲明'拋出RuntimeException' ,我認爲你的意思是拋出異常。 –

+0

這兩個工作。但爲了一般性,'拋出異常'更好。 – ItamarG3

+1

和捕捉RuntimeException將不會修復編譯器錯誤在這種情況下,或者 – luk2302