Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

En oversikt over klasser og metoder for alle oppgavene er gitt i vedlegg 1. Kommentarene inneholder krav til de ulike delene, som du må ta hensyn til når du løser oppgavene. I tillegg til metodene som er oppgitt, står du fritt til å definere ekstra metoder for å gjøre løsningen ryddigere. Nyttige standardklasser og -metoder finnes i vedlegg 32.

Temaet for oppgaven er et spisested (Diner) og problemstillingen er plassering (Seating) av grupper (Group) av gjester ved bordene (Table).

 

Expand
titleDel 1 - Group, Table- og Seating-klassene (15%)

Group-, Table- og Seating-klassene (vedlegg 1) er såkalte verdi-klasser, med data som skal oppgis ved opprettelsen av objektene og siden ikke skal kunne endres. Group skal inneholde data om antall gjester i gruppa, Table skal inneholde data om antall stoler (capacity) og Seating skal holde rede på bordet en gitt gruppe sitter på.

Oppgave a)

Skriv ferdig Group og Seating, inkludert nødvendige innkapslingsmetoder. 

Expand
titleLF
Code Block
public class Group {
 
       private final int guestCount;
 
       public Group(int guestCount) {
              this.guestCount = guestCount;
       }
 
       public int getGuestCount() {
              return guestCount;
       }
}
 
public class Seating {
 
       private final Table table;
       private final Group group;
 
       public Seating(Table table, Group group) {
              this.table = table;
              this.group = group;
       }
      
       public Table getTable() {
              return table;
       }
      
       public Group getGroup() {
              return group;
       }
}
Oppgave b)

En skal ikke kunne ha Seating-objekter for bord som ikke har mange nok stoler til hele gruppa som er plassert der. Skriv koden som trengs for å sikre at denne regelen overholdes.

Expand
titleLF

Følgende kode legges øverst i konstruktøren:

Code Block
if (table.getCapacity() < group.getGuestCount()) {
   throw new IllegalArgumentException("The table is too small for the group");
}

Viktig å utløse unntak, ikke bare en if rundt initialiseringskoden.

Oppgave c)

Anta at Group hadde en metode for å endre antall gjester. Forklar med tekst og/eller kode hvilke endringer du måtte gjort for å sikre at regelen i b) overholdes.

Expand
titleLF

Group måtte hatt en referanse til Seating-objektet (eller Table-objektet) som ble satt av Seating, så den kunne kjøre tilsvarende sjekk som over, ved endring av størrelsen. Uten en slik referanse hjelper det ikke å si at en skal sjekke den nye gruppestørrelsen opp mot antall stoler ved bordet. En kan til nød bruk observatør-observert-teknikken, men det er overkill her.

 

Oppgave d)

I tillegg til antall stoler, skal et bord ha et bordnummer. Dette skal være et unikt løpenummer som ikke oppgis, men settes automatisk av kode i Table-klassen selv når Table-objekter opprettes. Det aller første bordet som lages skal få 1 som nummer, det andre skal få 2 osv. Implementer konstruktøren og annen nødvendig kode, inkludert getNum-metoden!

Expand
titleLF

Her er poenget at en trenger en global teller, som en får til i Java ved bruk av static. Denne må brukes og økes i Table sin konstruktør.

Code Block
private static int tableCounter = 1; 
 
private final int num;
private final int capacity;
 
public Table(int capacity) {
       this.num = tableCounter++;
       this.capacity = capacity;
}

...

Expand
titleAppendix 1: Provided code (fragments)
Code Block
// part 1
 
/**
 * A group (of people) dining together, and should be seated at the same table.
 * We currently only need to handle the size. 
 */
public class Group {
 
       /**
       * Initializes this Group with the provided guest count
       */
       public Group(int guestCount) {
              ...
       }
}
 
/**
 * A table with a certain maximum capacity.
 */
public class Table {
 
       /**
       * Initializes this Table with the provided capacity.
       * The table is also assigned a unique number.
       * @param capacity
       */
       public Table(int capacity) {
              ...
       }
 
       /**
       * @return the table number
       */
       public int getNum() {
              ...
       }
}
 
/**
 * Represents the fact that a Group is seated at and occupies a Table
 */
public class Seating {
 
       /**
       * Initializes this Seating ...
       */
       public Seating(...) {
              ...
       }
}

 
// part 2
 
/**
 * A place where groups of guests can buy a meal
 */
public class Diner {
 
       /**
       * Tells whether a Table is occupied.
       * @param table the Table to check
       * @return true if anyone is sitting at the provided Table
       */
       public boolean isOccupied(Table table) {
              ...
       }
      
       /**
       * Computes the guest capacity,
        * either the remaining (includeOccupied == false) or total (includeOccupied == true).
       * @param includeOccupied controls whether to include tables that are occupied.
       * @return the guest capacity
       */
       public int getCapacity(boolean includeOccupied) {
              ...
       }
      
       /**
       * Adds a table to this Diner
       * @param table
       */
       public void addTable(Table table) {
              ...
       }
 
       /**
       * Removes a Table from this Diner.
       * If the table is occupied an IllegalArgumentException exception should be thrown.
       * @param table
       * @throws IllegalArgumentException
       */
       public void removeTable(Table table) {
              ...
       }
      
       /**
       * Merges two tables, i.e. replaces two tables with one table.
       * lostCapacity is the difference between the old capacity and the new.
       * This number is typically positive, since seats are lost when moving two tables
        * close to each other.
       * @param table1
       * @param table2
       * @param lostCapacity
       * @throws IllegalArgumentException if any of the tables are occupied
       */
       public void mergeTables(Table table1, Table table2, int lostCapacity) {
              ...
       }
 
       /**
       * Splits a table into two, i.e. replaces one tables with two tables.
       * The two capacities are the capacities of the two new tables.
       * @param table
       * @param capacity1
       * @param capacity2
       * @throws IllegalArgumentException if the table is occupied
       */
       public void splitTable(Table table, int capacity1, int capacity2) {
              ...
       }
 
       /**
       * Tells whether a table has the provided capacity,
       * i.e. if that number of new guests can be seated there.
       * Note that a table cannot be shared among different groups.
       * @param table
       * @param capacity
       * @return true of capacity number of guests can be seated here, false otherwise.
       */
       public boolean hasCapacity(Table table, int capacity) {
              ...
       }
 
       /**
       * Returns the tables that has the provided capacity.
       * The tables should be sorted with the one with the least capacity (but enough) first.
       * @param capacity
       * @return the tables that has the provided capacity
       */
       public Collection<Table> findAvailableTables(int capacity) {
              ...
       }
      
       /**
       * Finds a suitable, existing table for the provided group, and creates
       * (but doesn't add) a corresponding Seating.
       * The chosen table should be the one with the least capacity.
       * @param group the group to be seated
       * @return the newly created Seating
       */
       public Seating createSeating(Group group) {
              ...
       }
      
       /**
       * Creates and adds a Seating for the provided group, using the createSeating method.
       * @param group
       * @return true if a Seating was created and added, false otherwise.
       */
       public boolean addSeating(Group group) {
              ...
       }
      
       /**
       * Removes the seating for the provided table (number), if one exists
       * @param tableNum the number of the table to be removed
       */
       public void removeSeating(int tableNum) {
              ...
       }
}
 

// part 3
 
public class SimpleTable ... Table {
 
       public SimpleTable(int capacity) {
              ...
       }
 
       ...
}
 
/**
 * A table that consists of two other tables.
 */
public class CompositeTable ... Table {
      
       public CompositeTable(Table table1, Table table2, int lostCapacity) {
              ...
       }
 
       ...
}
 
// part 4
 
/**
 * Interface for listening to changes in Diner capacity
 */
public interface CapacityListener {
       /**
       * Called to inform that a Diner has changed capacity
       * @param diner
       */
       public void capacityChanged(Diner diner);
}
 
/**
 * Handles guests arriving at and departing from a Diner.
 */
public class GuestManager ... {
 
       public GuestManager(Diner diner) {
              ...
       }
      
       /**
       * Handles arriving groups, by either seating them immediately
       * (if possible) or putting them in queue. Those enqueued will
       * be seated when the Diner's (change in) capacity allows.
       * @param group
       */
       public void groupArrived(Group group) {
              ...
       }
 
       /**
       * Handles departing groups, by removing their seating.
       * @param tableNum the table where the group was seated
       */
       public void groupDeparted(int tableNum) {
              ...
       }
 
       ...
}

 

...

Expand
titleAppendix 2: Standard Java classes and methods

interface Iterable<T>

Iterator<T>

iterator() Returns an iterator over elements of type T.

public interface Collection<E> extends Iterable<E>

boolean

add(E e) Ensures that this collection contains the specified element.

boolean

addAll(Collection<? extends E> c) Adds all of the elements in the specified collection to this collection.

void

clear() Removes all of the elements from this collection.

boolean

contains(Object o) Returns true if this collection contains the specified element.

boolean

containsAll(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.

boolean

isEmpty() Returns true if this collection contains no elements.

boolean

remove(Object o) Removes a single instance of the specified element from this collection, if it is present.

boolean

removeAll(Collection<?> c) Removes all of this collection's elements that are also contained in the specified
collection.

boolean

removeIf(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate.

boolean

retainAll(Collection<?> c)

Retains only the elements in this collection that are contained in the specified collection.

int

size() Returns the number of elements in this collection.

Stream<E>

stream() Returns a sequential Stream with this collection as its source.

interface List<E> extends Collection<E>

void

add(int index, E element) Inserts the specified element at the specified position in this list.

boolean

addAll(int index, Collection<? extends E> c) Inserts all of the elements in the specified collection into this list at the
specified position.

E

get(int index) Returns the element at the specified position in this list.

int

indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if it does not
contain the element.

int

lastIndexOf(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if it does not
contain the element.

E

remove(int index) Removes the element at the specified position in this list.

E

set(int index, E element) Replaces the element at the specified position in this list with the specified element.

Void

sort(Comparator<? super E> c) Sorts this list according to the order induced by the specified Comparator.

interface Map<K,V>

void

clear() Removes all of the mappings from this map.

boolean

containsKey(Object key) Returns true if this map contains a mapping for the specified key.

V

get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the
key.

boolean

isEmpty() Returns true if this map contains no key-value mappings.

Set<K>

keySet() Returns a Set view of the keys contained in this map.

V

put(K key, V value) Associates the specified value with the specified key in this map.

void

putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map.

V

remove(Object key) Removes the mapping for a key from this map if it is present.

int

size() Returns the number of key-value mappings in this map.

interface Stream<T>

boolean

allMatch(Predicate<? super T> predicate) Returns whether all elements of this stream match the provided predicate.

boolean

anyMatch(Predicate<? super T> predicate) Returns whether any elements of this stream match the provided
predicate.

<R,A> R

collect(Collector<? super T,A,R> collector) Performs a mutable reduction operation on the elements of this
stream using a Collector.

Stream<T>

filter(Predicate<? super T> predicate) Returns a stream consisting of the elements of this stream that match
the given predicate.

void

forEach(Consumer<? super T> action) Performs an action for each element of this stream.

Stream<R>

map(Function<? super T,? extends R> mapper) Returns a stream consisting of the results of applying the given
function to the elements of this stream.

T

reduce(T identity, BinaryOperator<T> accumulator) Performs a reduction on the elements of this stream, using
the provided identity value and an associative accumulation function, and returns the reduced value.

Stream<T>

sorted() Returns a stream consisting of the elements of this stream, sorted according to natural order.

Stream<T>

sorted(Comparator<? super T> comparator) Returns a stream consisting of the elements of this stream, sorted
according to the provided Comparator.

class String implements Comparable<String>

char

charAt(int index) Returns the char value at the specified index.

boolean

contains(String s) Returns true if and only if this string contains the specified string.

boolean

endsWith(String suffix) Tests if this string ends with the specified suffix.

static String

format(String format, Object... args) Returns a formatted string using the specified format string and arguments.

int

indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.

int

indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character,

starting the search at the specified index.

int

indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.

int

indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.

boolean

isEmpty() Returns true if, and only if, length() is 0.

int

lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.

int

lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.

int

lastIndexOf(String str) Returns the index within this string of the last occurrence of the specified substring.

int

lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.

int

length() Returns the length of this string.

String

replace(String target, String replacement) Replaces each substring of this string that matches the literal target
string with the specified literal replacement string.

String[]

split(String regex) Splits this string around matches of the given regular expression.

boolean

startsWith(String prefix) Tests if this string starts with the specified prefix.

String

substring(int beginIndex) Returns a string that is a substring of this string.

String

substring(int beginIndex, int endIndex) Returns a string that is a substring of this string.

String

toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.

String

toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.

String

trim() Returns a string whose value is this string, with any leading and trailing whitespace removed.

class Scanner

Scanner(InputStream source)

Constructs a new Scanner that produces values scanned from the specified input stream.

void

close() Closes this scanner.

boolean

hasNext() Returns true if this scanner has another token in its input.

boolean

hasNextBoolean() Returns true if the next token in this scanner's input can be interpreted as a boolean value using a
case insensitive pattern created from the string "true|false".

boolean

hasNextDouble() Returns true if the next token in this scanner's input can be interpreted as a double using nextDouble().

boolean

hasNextInt() Returns true if the next token in this scanner's input can be interpreted as an int using nextInt().

boolean

hasNextLine() Returns true if there is another line in the input of this scanner.

String

next() Finds and returns the next complete token from this scanner.

boolean

nextBoolean() Scans the next token of the input into a boolean value and returns that value.

double

nextDouble() Scans the next token of the input as a double.

int

nextInt() Scans the next token of the input as an int.

String

nextLine() Advances this scanner past the current line and returns the input that was skipped.