Lecture 8, solutions
Exercise 1.
According to the API, sort throws ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers), and UnsupportedOperationException - if the specified list's list-iterator does not support the set.
Exercise 2.1
se ppt filExercise 2.2
Da ExceptionC er en subclasse af ExceptionA skal denne catches før ExceptionA.Exercise 3.1
public class MyDate implements Date{ static final int[] daysInMonth={31,28,31,30,31,30,31,31,30,31,30,31,}; public MyDate(int y, int m, int d) throws DateException{ // Constructor might throw exception setDate(y, m, d); } public void setDate(int y, int m, int d) throws DateException{ year = y; if (m<1 || m>12) throw new DateException("wrong month"); month = m; if (d<1 || d> daysInMonth[m-1]) throw new DateException("wrong day"); day = d; } public int getYear(){return year;} public int getMonth(){return month;} public int getDay(){return day;} public String toString(){ return day +"/"+month+"/"+year; } }
Exercise 3.2.1
public static void main(String args[]) throws Date.DateException { System.out.println("The date is: " + editDate(new MyDate(2004,6,15)) ); }A null is returned...
Exercise 3.2.2
private void storeDate(){ int y,m,d; try{ try{y = Integer.parseInt(yearField.getText());} catch(NumberFormatException nfe){ messages.setText("Year is not a number"); return; } try{m = Integer.parseInt(monthField.getText());} catch(NumberFormatException nfe){ messages.setText("Month is not a number"); return; } try{d = Integer.parseInt(dayField.getText());} catch(NumberFormatException nfe){ messages.setText("Day is not a number"); return; } date.setDate(y,m,d); this.hide(); }catch(Throwable uups){ messages.setText("Something is not right!?"); } }
Exercise 3.2.3
The only thing to change in MyDate is the setDate method.
public void setDate(int y, int m, int d) throws DateException{ year = y; if (m<1 || m>12) throw new DateException("month"); month = m; if (d<1 || d> daysInMonth[m-1]) throw new DateException("day"); day = d; }
The storeDate method is changed to:
private void storeDate(){ int y,m,d; try{ try{y = Integer.parseInt(yearField.getText());} catch(NumberFormatException nfe){ messages.setText("Year is not a number"); return; } try{m = Integer.parseInt(monthField.getText());} catch(NumberFormatException nfe){ messages.setText("month is not a number"); return; } try{d = Integer.parseInt(dayField.getText());} catch(NumberFormatException nfe){ messages.setText("day is not a number"); return; } date.setDate(y,m,d); this.hide(); }catch(MyDate.MyDateException e){ if ( e.field.equals("month") ) messages.setText("Wrong month number"); else messages.setText("Wrong day number"); }catch(Throwable uups){ messages.setText("Something is not right!?"); } }