LULEÅ TEKNISKA UNIVERSITET Tentamen i Program och datastrukturer Totala antalet uppgifter: 5 Lärare: Håkan Jonsson, Johan Karlsson, Tomas Johansson, (1700, 2016, 1465) Resultatet anslås senast 2004-04-01 i A-huset. Kurskod SMD135 (SMD064) Datum 2004-03-18 Skrivtid 4 tim Tillåtna hjälpmedel: Inga. Bilagor: Kodexempel och dokumentation. Varje uppgift ges först på svenska och sen på engelska. Eventuella exempel återfinns alltid sist i uppgiften och då endast på engelska. Tänk noga efter vad som ska döljas respektive vara synligt utanför klassen. Var noga med att objekts inre tillstånd inte exponeras så att de kan förändras utifrån där det inte är lämpligt. 1. Teori a) Synlighet (3p) Det finns tre olika nyckelord i Java för att specificera vilken synlighet en variabel eller metod skall ha. Vidare så anges en fjärde synlighet genom frånvaro av de tre ovan nämnda nyckelorden. Räkna upp de tre nyckelorden. Förklara de fyra olika varianterna av synlighet. b) Polymorfism (1p) I bilaga A finns de fem klasserna A, B, C, D och E beskrivna. Vad skrivs ut när följande (fungerande) programsatser utförs?... B b; // Declares the variable b b = new D(); System.out.println(b);... c) Tidskomplexitet (1p) Vilken är tidskomplexiteten för insättningssortering respektive mergesort i värsta fallet? English version a) Visibility (3p) In Java there are three different keywords to specify the scope of a variable or method. There is a fourth scope restriction in Java that is specified by the absence of a scope keyword. Name the three keywords. Explain the four variants of scope visibility. b) Polymorphism (1p) In Appendix A the five classes A, B,C, D, and E are described. What is printed when the following (working) code is executed?... B b; // Declares the variable b b = new D(); System.out.println(b);... c) Time complexity (1p) What is the worst-case time complexity of insertion sort and mergesort respectively?
2. Festival Till ett program som ska simulera en festival (t ex Roskilde, Hultsfreds, Arvika etc) behövs en klass Visitor för att representera besökare. Varje besökare har ett unikt biljettnummer och en historik som växer i storlek under simuleringen. Din uppgift är att implementera denna klass enligt följande. När ett besökarobjekt skapas ska det tilldelas ett unikt biljettnummer. Detta representeras av ett heltal och klassen ska ha en metod public int number() som returnerar numret. Historiken är en lista med strängar som beskriver de musikband som besökaren lyssnat på under festivalen. De ska representeras med listor av typen LinkedList som finns bifogad i Appendix B (och om du vill utökad med iteratorn i uppgift 4). Ordningen mellan strängarna i listan är inte viktig. Det enda som är känt om musikband är att de är instanser av (den okända) klassen Band och att de beskrivs av den sträng som tostring ger tillbaka. Visitor ska ha en metod public LinkedList history() som ger som resultat en besökares historik. Den ska också innehålla en metod public void addband(band b) som lägger till ytterligare ett musikband till historiken. Annars ska historiken endast kunna förändras inifrån Visitor. Du får använda iteratorn ur uppgift 4 även om du inte lyckats lösa uppgiften. English version For a program that will be used to simulate a festival a class Visitor is needed to represent visitors. Each visitor gets a unique ticket number and has a history that grows in size as the simulation proceeds. You task is to implement this class as follows. When a visitor-object is created, it should be assigned a unique ticket number. Such numbers are represented by integers and the class should contain a method public int number() that returns the integer. The history is a list of strings that describe the music bands the visitor has listened to. Histories should be represented by lists of the type LinkedList that you find in Appendix B (together with the iterator added in Problem 4, if you like). The order between the strings does not matter in the lists. The only thing that is known about music bands is that they are objects of the (unknown) class Band and that they are described by a string that is returned by tostring. Visitor should have a method public LinkedList history() that gives the history of a visitor. It should also contain a method public void addband(band b) that adds yet another music band to the history. Apart from this method a history should only be possible to change from within the class Visitor. You may use the iterator in Problem 4 even if you have not solved that problem. (5p)
3. Inheritance and exceptions (5p) «abstract» LiquidContainer +LiquidContainer(size:int) +open(): void +sip(): void +gulp(): void +isempty(): boolean +isopen(): boolean IsClosedException IsEmptyException throws Can +Can(size:int) +sip(): void Bottle +Bottle(size:int) +close(): void +sip(): void Figure 1: UML diagram for Problem 3. Implementera de tre klasser för olika slags vätskebehållare som beskrivs i UMLdiagrammet ovan enligt följande. Den abstrakta klassen LiquidContainer: En konstruerare som tar storleken på behållaren som ett positivt heltalsargument och skapar en helt fylld, stängd, behållare. isempty() som kontrollerar om behållaren är tom eller ej. En abstrakt metod sip() som representerar att man tar en slurk och minskar innehållet. Implementeringar av denna ska kasta ett undantag IsClosedException om behållaren är stängd och IsEmptyException om behållaren är öppen men tom. gulp() som tar 10 slurkar ur behållaren (oavsett hur sip() är deklarerad). open() som öppnar behållaren. Om den redan är öppen händer ingenting. isopen() som avgör om behållaren är öppen eller ej. Underklassen Can: En konstruerare som fungerar på samma sätt som superklassens konstruerare. En implementation av sip() som minskar innehållet med 1 enhet. Underklassen Bottle: En konstruerare som fungerar på samma sätt som superklassens konstruerare. En implementation av sip() som minskar innehållet med 2 enheter. En metod close() som stänger flaskan (om den redan är stängd händer ingenting). Du får anta att klasserna som representerar undantagen redan är skrivna. Tips: Deklarera variabler i superklassen (LiquidContainer) för att hålla rätt på aktuell volym och om behållaren är öppen eller ej. Dessa variabler måste även synas i underklasserna. (English version on next page)
English version Implement the three classes for various kinds of containers that are described in the UML diagram (Figure 1). The abstract class LiquidContainer: A constructor that takes the size of the container as an argument and creates a completely filled, closed, container. isempty() that checks whether the container is empty or not. An abstract methodsip() that represents that a sip is taken from the container. This decreases the contents. Implementations of this method should throw an IsClosedException if the container is closed and an IsEmptyException if the container is open but empty. gulp() that results in ten (10) sips being taken from the container. open() that opens the container (if it s already open nothing happens). isopen() that decides whether the container is open or not. The subclass Can: A constructor that works the same way as the constructor of the super class. A implementation of sip() that decreases the contents by 1 unit. The subclass Bottle: A constructor that works the same way as the constructor of the super class. A implementation of sip() that decreases the contents by 2 units. A method close() that closes the container (if it s already closed nothing happens). You can assume that the classes that represent the exceptions have already been written. Hint: Declare variables in the super class (LiquidContainer) that keep track of the current volume and whether the container is open or not. Make sure these variables are also visible in the subclasses.
4. Listiterator Din uppgift består av att implementera en iterator för klassen LinkedList som finns i Appendix B. Iteratorn ska realisera interfacet Iterator från Javas API (se Appendix C). remove() skall kasta undantaget UnsupportedOperationsException. Lägg till en metod i klassen LinkedList som returnerar en iterator. Metoden skall ha följande signatur: public Iterator iterator(). Du får lägga till ny kod i LinkedList klassen men inte ändra på någon existerande kod. (Svara bara med dina tillägg.) English version Your task is to implement an iterator for the LinkedList class in Appendix B. The iterator should realize the Iterator interface from the Java API in Appendix C. remove() should throw the exception UnsupportedOperationsException. Add a method in the LinkedList class which returns an iterator. The Method should have the following signature: public Iterator iterator(). You are allowed to add new code to the LinkedList class but you may not modify any existing code. (Only answer with your additions.) 5. Grammar Skriv en parser som undersöker huruvida indatat följer reglerna för nedanstående grammatik: <pexpr> ::= "(" <pexpr> ")" <pexpr> "{" <pexpr> "" <pexpr> empty Parserklassen är redan delvis skriven. Din uppgift är att skriva koden för metoden private static boolean pexpr(), så att den returnerar true om indatat följer grammatikreglerna, och false om den inte gör det. Använd tokenizern i appendix D. English version Write a parser that checks whether an input follows the rules of the following grammar: <pexpr> ::= "(" <pexpr> ")" <pexpr> "{" <pexpr> "" <pexpr> empty The parser class is already partially written. Your task is to write the code for the method private static boolean pexpr(), so that it returns true if the input follows the grammar rules, andfalse if it doesn t. Use the tokenizer in Appendix D. public abstract class ParaExpr { private static Tokenizer token ; public static boolean accept ( Reader input ) { boolean ok ; token = new Tokenizer ( input ) ; token. get ( ) ; ok = pexpr ( ) ; return ok ; (5p) (5p) private static boolean pexpr () { // Add your code here. Listing 1: ParaExpr.java
A Classes for Problem 1b public class A { public A(){ public String tostring (){ return A ; public class B extends A { public B(){ public String tostring (){ return B ; public class C extends B { public C(){ public String tostring (){ return C ; public class D extends C { public D(){ public String tostring (){ return D ; public class E extends D { public E(){ public String tostring (){ return E ; Listing 2: Classes for Problem 1b.
B LinkedList.java import java. u t i l. NoSuchElementException ; / The Linked List class. @ version 2004 03 15 @author Johan Karlsson public class LinkedList { private Node sentinel ; Creates an empty LinkedList. public LinkedList () { sentinel = new Node(null, null, null ) ; sentinel. setnext ( sentinel ) ; sentinel. setprev ( sentinel ) ; Add an item to the end of this l i s t. @param item the item to insert in this l i s t. public void add( Object item ) { Node n = new Node( sentinel, sentinel. prev (), item ) ; sentinel. setprev (n ) ; n. prev ( ). setnext (n ) ; Inspects the item at the front of this l i s t. @return the item at the front of this l i s t. @exception NoSuchElementException i f this l i s t is empty. public Object f i r s t () { if ( isempty ()) throw new NoSuchElementException( f i r s t : empty l i s t ) ; return sentinel. next ( ). item ( ) ; Removes the item at the front of this l i s t. @exception NoSuchElementException i f this l i s t is empty. public void removefirst () { if ( isempty ()) throw new NoSuchElementException( removefirst : empty l i s t ) ; sentinel. setnext ( sentinel. next ( ). next ( ) ) ; sentinel. next ( ). setprev ( sentinel ) ; Tests i f this l i s t is empty. @return true i f this l i s t is empty, otherwise false. public boolean isempty () { return sentinel == sentinel. next ( ) ;
The node class represent a node in a doubly linked l i s t. @ version 2004 03 15 @author Johan Karlsson private class Node { private Node next ; private Node pr ev ; private O bject item ; Creates a node with next, prev and item set. @param n the next node. @param p the previous node. @param i the item in this node. private Node(Node n, Node p, Object i ) { next = n ; prev = p ; item = i ; Set the next node of this node. @param n the next node. private void setnext (Node n) { next = n ; Set the prev node of this node. @param p the prev node. private void setprev (Node p) { prev = p ; Inspect the next node. @return the next node. private Node next () {return next ; Inspect the prev node. @return the prev node. private Node prev () {return prev ; Inspect the item of this node. @return the item of this node. private Object item () {return item ; Listing 3: LinkedList.java
C Java API: Iterator Iterator (Java 2 Platform SE v1.4.2) http://www.cdt.luth.se/java/doc/jdk1.4.2/api/java/util/iterator.htm... Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Java TM 2 Platform Std. Ed. v1.4.2 java.util Interface Iterator All Known Subinterfaces: ListIterator All Known Implementing Classes: BeanContextSupport.BCSIterator public interface Iterator An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework. Since: 1.2 See Also: Collection, ListIterator, Enumeration Method Summary boolean hasnext() Returns true if the iteration has more elements. Object next() Returns the next element in the iteration. void remove() Removes from the underlying collection the last element returned by the iterator (optional operation). Method Detail hasnext public boolean hasnext() Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.) 1 of 2 03/15/04 17:08
Iterator (Java 2 Platform SE v1.4.2) http://www.cdt.luth.se/java/doc/jdk1.4.2/api/java/util/iterator.htm... Returns: true if the iterator has more elements. next public Object next() Returns the next element in the iteration. Returns: the next element in the iteration. Throws: NoSuchElementException - iteration has no more elements. remove public void remove() Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. Throws: UnsupportedOperationException - if the remove operation is not supported by this Iterator. IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method. Overview Package Class Use Tree Deprecated Index Help PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes SUMMARY: NESTED FIELD CONSTR METHOD DETAIL: FIELD CONSTR METHOD Java TM 2 Platform Std. Ed. v1.4.2 Submit a bug or feature For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright 2003 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy. 2 of 2 03/15/04 17:08
D Tokenizer.java import java. io. ; public class Tokenizer { private StreamTokenizer tokens ; protected i nt type ; public static final int ID = 1, NUMBER = 2, RIGHTPAREN = 3, LEFTPAREN = 4, ENDOFFILE = 5, PLUS = 6, MINUS = 7, ASTR = 8, SLASH = 9, LEFTBRACE = 10, RIGHTBRACE = 11, ILLEGAL = 1; public Tokenizer ( Reader input ) { tokens = new StreamTokenizer ( input ) ; tokens. ordinarychar ( ) ; tokens. ordinarychar ( / ) ; public void get () { try {type = tokens. nexttoken ( ); catch ( IOException e ) {throw new RuntimeException ( e. tostring ( ) ) ; public int kind () { switch ( type ) { case Str ea mto kenizer.tt WORD : return ID ; case Str ea mto kenizer.tt NUMBER : return NUMBER; case Str ea mto kenizer. TT EOF : return ENDOFFILE; default : switch ((char) type ) { case ( : return LEFTPAREN; case ) : return RIGHTPAREN; case + : return PLUS; case : return MINUS; case : return ASTR; case / : return SLASH; case { : return LEFTBRACE; case : return RIGHTBRACE; default : return ILLEGAL; public String ident () {return tokens. sval ; public double numbervalue () {return (double) tokens. nval ; public String tostring () {return tokens. tostring ( ); Listing 4: Tokenizer.java