// see // http://www.inf.unibz.it/~calvanese/teaching/exams/ip-java/written-exams/computer-science/2005-02-02/spec-cs-6-cfu.html public class LetterQueue { private String city; private String[] letters; private int firstfree; // this is the first free position // 0 ... firstfree - 1 are filled with letters public LetterQueue(String n, int s) { city = n; letters = new String[s]; firstfree = 0; } public String getCity() { return city; } public int size() { return letters.length; } public void newLetter(String m) throws Exception { if (firstfree < letters.length) { letters[firstfree] = m; firstfree++; } else { throw new Exception(); } } public String firstLetter() throws Exception { if (firstfree > 0) { return letters[0]; } else { throw new Exception(); } } public void removeLetter() throws Exception { if (firstfree > 0) { int j = 0; while (j < firstfree - 1) { letters[j] = letters[j + 1]; j++; } firstfree--; } else { throw new Exception(); } } public int numLetters() { return firstfree; } public String letter(int i) throws Exception { if (i >= 0 && i < firstfree) { return letters[i]; } else { throw new Exception(); } } public int[] shortLetters(int len) { int i; int count = 0; for (i = 0; i < firstfree; i++) { if (letters[i].length() < len) { count++; } } int results[] = new int[count]; int r = 0; for (i = 0; i < firstfree; i++) { if (letters[i].length() < len) { // we have found that mail number i is short results[r] = i; r++; } } return results; } public static void main(String a[]) { try { LetterQueue q = new LetterQueue("Bolzano", 100); System.out.println(q.getCity() + ": " + q.numLetters() + " out of " + q.size()); q.newLetter("Bersan: hello!"); // 1 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 0 queued now q.newLetter("Foruzan: dont know"); q.newLetter("Shogofa: bolzano is a green city"); // 2 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 1 queued now q.newLetter("Lecha: let's party"); // 2 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 1 queued now q.newLetter("Khuseyn: good bye"); q.newLetter("Albert: big mountains"); // 3 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 2 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 1 queued now System.out.println("delivered: " + q.firstLetter()); q.removeLetter(); // 0 queued now // the following should throw an exception q.removeLetter(); } catch (Exception e) { System.out.println("got an exception while calling my letter methods..."); } } }