2016-11-12 3 views
-1

Я получаю следующую ошибку при попытке скомпилировать этот код, который должен создать пользовательский массив Java, который не использует дженерики. Я уверен, что это не так, чтобы не создавать массив должным образом, но я не уверен.Как вызвать пользовательский массив Java

Любая помощь была бы действительно оценена! Благодаря!

Текущий Compile Отрывок Ошибка:

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 выбрасывает исключения могут, делая это:

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' , Я думаю, вы имеете в виду 'throws Exception'. –

+0

Обе работы. но для общности «лучше выбрасывает исключение». – ItamarG3

+1

и улавливание RuntimeException не исправит ошибку компилятора в этом случае либо – luk2302