Erste Version für alle A Testate

This commit is contained in:
2025-08-12 15:45:03 +02:00
parent edae167d26
commit e884fbca5f
58 changed files with 4290 additions and 192 deletions
+10
View File
@@ -0,0 +1,10 @@
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können. Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
+68
View File
@@ -0,0 +1,68 @@
import os
import textwrap
def read_wrapped_content(file, width=80):
content = file.read()
lines = content.split('\n')
wrapped_lines = []
for line in lines:
if line.strip():
wrapped_lines.append(textwrap.fill(line, width=width))
else:
wrapped_lines.append('')
return '\n'.join(wrapped_lines)
def create_output(testat_index=1, testat_version="a", max_line_length=80, separator="="):
title = f"Testat {testat_index} {testat_version}"
current_dir = os.path.dirname(os.path.abspath(__file__))
tasks_path = os.path.join(current_dir, f"subtasks/{testat_index}/{testat_version}")
output_path = os.path.join(current_dir, "output")
output_name = f"Aufgabenstellung Testat {testat_index} {testat_version}.txt"
disclaimer_path = os.path.join(os.path.dirname(__file__), "disclaimer.txt")
disclaimer_content = ""
print(f"Reading disclaimer from: {disclaimer_path}")
with open(disclaimer_path, "r") as disclaimer_file:
disclaimer_content = read_wrapped_content(disclaimer_file, max_line_length)
sections = [title, disclaimer_content]
for file_name in sorted(os.listdir(tasks_path)):
if file_name.endswith(".txt"):
file_path = os.path.join(tasks_path, file_name)
with open(file_path, "r") as file:
wrapped_content = read_wrapped_content(file, max_line_length)
sections.append(wrapped_content)
os.makedirs(output_path, exist_ok=True)
output_file_path = os.path.join(output_path, output_name)
with open(output_file_path, "w") as output_file:
s = "\n\n" + max_line_length * separator + "\n\n"
output_file.write(s.join(sections))
print(f"Generated output file: {output_file_path}")
def create_all_outputs():
current_dir = os.path.dirname(os.path.abspath(__file__))
tasks_path = os.path.join(current_dir, "subtasks")
for testat_dir in sorted(os.listdir(tasks_path)):
testat_path = os.path.join(tasks_path, testat_dir)
if os.path.isdir(testat_path):
try:
testat_index = int(testat_dir)
for version_dir in sorted(os.listdir(testat_path)):
version_path = os.path.join(testat_path, version_dir)
if os.path.isdir(version_path):
print(f"Generating output for Testat {testat_index} {version_dir}")
create_output(testat_index, version_dir)
except ValueError:
print(f"Skipping non-numeric directory: {testat_dir}")
if __name__ == "__main__":
create_all_outputs()
@@ -0,0 +1,42 @@
Testat 0 a
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
Aufgabe 1
Es sind zwei Klassen vorgegeben: Die Klasse Person und die Klasse Book.
----- a) -----
Die Klasse Book hat Felder für den Titel, den Autor und das Erscheinungsjahr
eines Buches, sowie einen passenden Konstruktor. Implementieren Sie die Methode
getInfo(), die einen String zurückgeben soll, der folgendermaßen aufgebaut ist:
<Vorname des Autors> <Nachname des Autors>: <Titel> (<Erscheinungsjahr>)
also zum Beispiel
Douglas Adams: The Hitchhiker's Guide to the Galaxy (1979)
----- b) -----
In der Klasse Book ist bereits die Methode getAge() definiert. Implementieren
Sie diese Methode so, dass sie das Alter eines Buches in Jahren zurückgibt.
Gehen Sie dabei davon aus, dass das aktuelle Jahr 2016 ist.
@@ -0,0 +1,120 @@
Testat 1 a
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
Aufgabe 1 - 25 Punkte
Die Methode calculateMeanAbove der Klasse Testat1A soll für alle Werte des
übergebenen Arrays arr, welche GRÖßER ALS der Grenzwert threshold sind, den
Durchschnitt berechnen.
Für die volle Punktzahl müssen Sie berücksichtigen, dass der Array arr auch null
oder leer sein kann. In diesem Fall soll 0 zurückgegeben werden.
Hinweis: Beachten Sie, dass eine Division durch 0 zu einem Fehler führt.
================================================================================
Aufgabe 2 - 25 Punkte
Die Methode calculateRowMean in der Klasse Testat1A erhält einen 2-dimensionales
Array, soll den Durchschnitt für jede Reihe berechnen und in einem neuen Array
zurückgeben.
Die erste Dimension des 2-dimensionalen Arrays addressiert die Reihe, die zweite
Dimension die Spalte. D.h. int x = arr[0][1] weist x den Wert der Reihe 0 und
der Spalte 1 zu.
In dem eindimensionalen Rückgabearray soll der Wert an der i-ten Stelle dem
Durchschnitt der i-ten Reihe entsprechen.
Für die volle Punktzahl müssen Sie folgendes beachten:
- Das übergebene 2-dimensionale Array kann null oder leer sein. In diesem Fall
soll ein leeres Array übergeben werden.
- Reihen innerhalb des 2-dimensionalen Arrays können null oder leer sein. In
diesem Fall soll für diese Reihe 0 im ausgegebenen Array gesetzt werden.
- Reihen innerhalb des 2-dimensionalen Arrays haben nicht notwendigerweise
dieselben Längen. Beachten Sie dies bei ihren Berechnungen.
Beispiel:
------- -----------------
|1|2|3| |(1+2+3)/3 = 2.0|
------- -----------------
|4|5|6| |(4+5+6)/3 = 5.0|
------- -----------------
|7|8|9| |(7+8+9)/3 = 8.0|
------- -----------------
Eingabe Rückgabe
================================================================================
Aufgabe 3 - 50 Punkte
In dieser Aufgabe sollen Sie die Klassen FridgeItem, Cheese und Yoghurt
anpassen. Die Schnittstelle Weightful ist vorgegeben und darf nicht verändert
werden.
Ergänzen Sie die Klasse FridgeItem wie folgt:
----- a) -----
Fügen Sie der Klasse 3 private Instanzvariablen hinzu: "weight" vom Typ double,
"name" vom Typ String und "color" vom Typ String.
----- b) -----
Initialisieren Sie diese Felder im vorgegebenen Konstruktor mit den Werten, die
dieser als Parameter erhält.
----- c) -----
Implementieren Sie die Schnittstelle Weightful und geben Sie in der zugehörigen
Methode den Wert der Instanzvariable "weight" zurück.
----- d) -----
Überschreiben Sie die toString() Methode aus java.lang.Object, so dass diese
eine Zeichenkette in folgendem Format zurückgibt: <name> (<color> <weight> g)
(also: Wert der Instanzvariable name, Leerzeichen, Klammer auf, Wert der
Instanzvariable color, Leerzeichen, Wert der Instanzvariable weight,
Leerzeichen, kleines g, Klammer zu)
Ergänzen Sie die Klassen Cheese und Yoghurt wie folgt:
----- e) -----
Ändern Sie die Vererbungsbeziehungen so, dass beide Klassen von FridgeItem
erben.
----- f) -----
Fügen Sie den Klassen den Konstruktor Ihrer neuen Superklasse hinzu und geben
Sie die Parameter an die Superklasse weiter.
----- g) -----
Überschreiben Sie die toString() Methode, so dass vor den Wert der
Implementierung aus der Superklasse noch der Name der Klasse gefolgt von einem
Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu FridgeItem soll
die Ausgabe wie folgt aussehen:
Cheese: <name> (<color> <weight> g) (für toString() in Cheese)
Yoghurt: <name> (<color> <weight> g) (für toString() in Yoghurt)
Nachdem Sie diese Änderungen gemacht haben, sollten alle Kompilierungsfehler
beseitigt sein.
@@ -0,0 +1,32 @@
Testat 1 b
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
================================================================================
================================================================================
@@ -0,0 +1,96 @@
Testat 2 a
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
Aufgabe 1 - Der Kühlschrank - 50 Punkte
Diese Aufgabe baut auf der Aufgabe des vorherigen Testats auf. Bearbeiten Sie
ausschließlich die Klasse Fridge.
Verändern Sie NICHT die Klassen Weightful, FridgeItem, Cheese und Yoghurt.
Die Klasse Fridge (Kühlschrank) speichert eine begrenzte Menge an FridgeItem
(Gegenständen) mit Hilfe eines "item"-Arrays. Die containsItem-Methode prüft, ob
sich ein Gegenstand bereits im Kühlschrank (d.h. im Array) befindet. Die
addItem-Methode fügt einen Gegenstand hinzu, sofern dieser nicht null ist und es
noch Platz gibt (also items.length < maxItems).
Erweitern Sie die Klasse wie folgt:
----- a) -----
Implementieren Sie die Schnittstelle Weightful und geben Sie über die getWeight-
Methode die Summe der Gewichte aller Gegenstände im Kühlschrank zurück.
----- b) -----
Ergänzen Sie die Prüfungen in der addItem-Methode so dass diese zusätzlich noch
sicherstellt, dass ein Gegenstand nur dann hinzugefügt wird.
– wenn er sich noch nicht im Kühlschrank befindet (Tipp: containsItem)
– wenn dadurch das maximale Gewicht (gespeichert in der Instanzvariable
"maxWeight") nicht überschritten wird (Tipp: getWeight).
----- c) -----
Implementieren Sie die Methode indexOf(name,startIndex), sodass diese das
FridgeItem mit dem Namen "name" im items-Array ab der Stelle "startIndex" bis
"items.length - 1" sucht. Wird ein FridgeItem mit dem Namen gefunden, soll der
kleinste Index zurückgegeben werden. Ist der Name nicht im Bereich von
"startIndex" bis "items.length - 1" enthalten, soll -1 zurückgegeben werden.
Einschränkung: Nutzen Sie für die Implementierung dieser Methode keinerlei
Schleifen, sondern ausschließlich Rekursion.
================================================================================
Aufgabe 2 - Deque - 50 Punkte
Eine doppelt verkette Liste (Doubly linked list) funktioniert wie die aus der
Vorlesung bekannte verkettete List (Linked list), der einzige Unterschied ist,
dass jedes Element zu dem Verweis auf das nächste Element auch noch ein Verweis
auf das vorherige Element hat.
Eine Deque (Double-ended queue) ist ähnlich zu einer Queue und einem Stack, sie
kombiniert die Eigenschaften beider Datentypen. Der einzige Unterschied ist,
dass Daten an beiden Enden gelesen, eingefügt und entfernt werden können.
In unserem Fall soll die Deque intern durch eine doppelt verkettete Liste
repräsentiert werden.
Implementieren Sie die folgenden Methoden in der Klasse Deque:
----- a) -----
void addLast(String): Diese Methode soll den übergebenen String ans Ende der
Deque anfügen.
Wenn der String null oder leer ist, soll nichts passieren.
----- b) -----
String peekFirst(): Diese Methode soll den ersten String der Deque zurückgeben
OHNE diesen zu entfernen.
Falls die Deque leer ist, soll null zurückgegeben werden.
----- c) -----
String pollLast(): Diese Methode soll den letzten String der Deque entfernen UND
zurückgeben.
Falls die Deque leer ist, soll null zurückgegeben werden.
----- d) -----
int size(): Diese Methode soll die aktuelle Anzahl der Strings in der Deque
zurückgeben.
Verändern Sie NICHT die anderen Methoden der Klasse Deque.
@@ -0,0 +1,21 @@
Testat 2 b
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -0,0 +1,125 @@
Testat 3 a
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
Aufgabe 1 - Baum - 60 Punkte
Die Klasse Tree implementiert einen geordneten Binärbaum, der intern mit der
Klasse TreeNode umgesetzt wird. Ein TreeNode besitzt hierfür einen double-Wert
(value), sowie ein linkes Kind (left) und ein rechtes Kind (right). Die Klasse
TreeVisitor speichert die Sequenz von TreeNodes, die über die visit-Methode an
TreeVisitor übergeben werden.
Implementieren Sie die folgenden Methoden in der Klasse Tree:
----- a) -----
void traverse(TreeVisitor visitor, TreeNode current)
Diese Methode soll den Teilbaum mit der Wurzel "current" vollständig ablaufen
(traversieren). Während der Traversierung, soll die Methode visit(TreeNode) am
übergebenen Visitor in der Hauptreihenfolge (pre-order) aufgerufen werden (d.h.
für jeden Teilbaum erst die Wurzel, dann den Teilbaum des linken Kinds und dann
den Teilbaum des rechten Kinds).
Tipp: Falls Sie die Hauptreihenfolge (pre-order) nicht verstehen, implementieren
Sie irgendeine vollständige Traversierung, um zumindest Teilpunkte zu erhalten.
----- b) -----
int count(double value, TreeNode current)
Diese Methode soll ausgehend von "current" die Anzahl der TreeNodes zählen,
deren Wert dem übergebenen "value" entspricht. Die Implementierung der Methode
soll dabei nur die Teilbäume weiterverfolgen, die den Wert auch enthalten
können. Beachten Sie dazu die Ordnung, die die insert-Methode in der Klasse Tree
definiert.
Tipp: Falls Ihnen die Umsetzung einer effizienten Implementierung nicht klar
ist, missachten Sie diese Anforderung, um zumindest Teilpunkte zu erhalten.
----- c) -----
int height()
Diese Methode soll die Höhe des gesamten Baums berechnen und zurückgeben.
Die Höhe eines Baums ist wie folgt definiert:
- Ein leerer Baum hat die Höhe 0.
- Ein einzelner Knoten hat die Höhe 1.
- Allgemein ist die Höhe eines Baums 1 plus die maximale Höhe seiner Teilbäume.
================================================================================
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
----- a) -----
void write(Path path, List<String> list)
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen
Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei
entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
----- b) -----
List<String> read(Path path)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben.
Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen.
Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse
java.nio.file.Files vorhanden sind.
================================================================================
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In
dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von
Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception
werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der
Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine
NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur
so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception genau der in der
Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen
vorliegenden Methoden lösbar.
@@ -0,0 +1,21 @@
Testat 3 b
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -0,0 +1,75 @@
Testat 4 a
================================================================================
WICHTIGE HINWEISE
- Verändern Sie die Signaturen der Methoden NICHT!
- Abgaben mit Syntax-Fehlern werden automatisch mit 0 Punkten bewertet.
- Vergessen Sie NICHT ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der Beste versucht wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten drüfen Sie Fragen an die
Aufsicht stellen.
- In der main-Methode der Klasse Main stellen wir Ihnen Testfälle zur Verfügung
mit denen Sie ihre Ergebnisse während der Entwicklung kontrollieren können.
Diese Testfälle sind jedoch NICHT alle Testfälle welche serverseitig ausgeführt
werden für die finale Bewertung. D.h. nur weil diese Testfälle bestehen erhalten
Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
================================================================================
Dieses Testat besteht aus der Schnittstelle Person sowie den Klassen Student,
Operation, LinkedList, ListItem und Main. Die Schnittstelle Person und die
Klasse ListItem sollen sie nicht verändern.
Die Klasse Main enthält eine main-Methode mit der Sie Ihre Implementierung
testen können.
================================================================================
Aufgabe 1 – Klassen, Variablen und Methoden (40 Punkte)
Erweitern Sie die Klasse Student wie folgt:
- Fügen Sie der Klasse zwei private Instanzvariablen hinzu: "name" vom Typ
String und "id" vom Typ long.
- Implementieren Sie die Schnittstelle Person, indem Sie den Inhalt der
entsprechenden Instanzvariablen in den dafür vorgesehenen Methoden zurückgeben.
- Implementieren Sie einen öffentlichen Konstruktor mit einem Parameter "name"
und einem Parameter "id" (in dieser Reihenfolge), der die Instanzvariablen mit
dem selben Namen initialisiert.
- Überschreiben Sie die equals-Methode aus der Klasse java.lang.Object, sodass
Studenten auf Basis ihrer "id" miteinander verglichen werden.
Wenn Sie mit dieser Aufgabe fertig sind, sollte die Klasse Main keine
Compilerfehler mehr aufweisen.
================================================================================
Aufgabe 2 – Arrays und Exceptions (20 Punkte)
Implementieren Sie die Methode double average(double[] values) in der Klasse
Operation, so dass diese den Durchschnitt der im Parameter "values" übergebenen
Werte berechnet und zurückliefert. Enthält "values" keine Werte oder ist
"values" null, soll Ihre Implementierung der average Methode eine
java.lang.IllegalArgumentException auslösen.
================================================================================
Aufgabe 3 – Verkettete Listen (40 Punkte)
Die Klasse LinkedList soll eine einfach verkettete Liste darstellen.
Implementieren Sie mit Hilfe der Definitionen in der Klasse ListItem die
folgenden Methoden der Klasse LinkedList:
- int size(): Diese Methode soll die Anzahl der Elemente in der Liste
zurückliefern.
- void prepend(String value): Diese Methode soll den übergebenen String "value"
an den Anfang der Liste einfügen. Der bisherige Listeninhalt soll dabei
natürlich erhalten bleiben und um eins nach hinten verschoben werden.
- String get(int i): Diese Methode soll den Wert des i-ten Elements in der Liste
zurückgeben.
Falls i kein gültiger Verweis auf ein Element der Liste ist, soll von Ihrer
Implementierung der Methode eine java.lang.IllegalArgumentException ausgelöst
werden.
@@ -0,0 +1,14 @@
Aufgabe 1
Es sind zwei Klassen vorgegeben: Die Klasse Person und die Klasse Book.
----- a) -----
Die Klasse Book hat Felder für den Titel, den Autor und das Erscheinungsjahr eines Buches, sowie einen passenden Konstruktor. Implementieren Sie die Methode getInfo(), die einen String zurückgeben soll, der folgendermaßen aufgebaut ist:
<Vorname des Autors> <Nachname des Autors>: <Titel> (<Erscheinungsjahr>)
also zum Beispiel
Douglas Adams: The Hitchhiker's Guide to the Galaxy (1979)
----- b) -----
In der Klasse Book ist bereits die Methode getAge() definiert. Implementieren Sie diese Methode so, dass sie das Alter eines Buches in Jahren zurückgibt. Gehen Sie dabei davon aus, dass das aktuelle Jahr 2016 ist.
@@ -0,0 +1,6 @@
Aufgabe 1 - 25 Punkte
Die Methode calculateMeanAbove der Klasse Testat1A soll für alle Werte des übergebenen Arrays arr, welche GRÖßER ALS der Grenzwert threshold sind, den Durchschnitt berechnen.
Für die volle Punktzahl müssen Sie berücksichtigen, dass der Array arr auch null oder leer sein kann. In diesem Fall soll 0 zurückgegeben werden.
Hinweis: Beachten Sie, dass eine Division durch 0 zu einem Fehler führt.
@@ -0,0 +1,24 @@
Aufgabe 2 - 25 Punkte
Die Methode calculateRowMean in der Klasse Testat1A erhält einen 2-dimensionales Array, soll den Durchschnitt für jede Reihe berechnen und in einem neuen Array zurückgeben.
Die erste Dimension des 2-dimensionalen Arrays addressiert die Reihe, die zweite Dimension die Spalte. D.h. int x = arr[0][1] weist x den Wert der Reihe 0 und der Spalte 1 zu.
In dem eindimensionalen Rückgabearray soll der Wert an der i-ten Stelle dem Durchschnitt der i-ten Reihe entsprechen.
Für die volle Punktzahl müssen Sie folgendes beachten:
- Das übergebene 2-dimensionale Array kann null oder leer sein. In diesem Fall soll ein leeres Array übergeben werden.
- Reihen innerhalb des 2-dimensionalen Arrays können null oder leer sein. In diesem Fall soll für diese Reihe 0 im ausgegebenen Array gesetzt werden.
- Reihen innerhalb des 2-dimensionalen Arrays haben nicht notwendigerweise dieselben Längen. Beachten Sie dies bei ihren Berechnungen.
Beispiel:
------- -----------------
|1|2|3| |(1+2+3)/3 = 2.0|
------- -----------------
|4|5|6| |(4+5+6)/3 = 5.0|
------- -----------------
|7|8|9| |(7+8+9)/3 = 8.0|
------- -----------------
Eingabe Rückgabe
@@ -0,0 +1,34 @@
Aufgabe 3 - 50 Punkte
In dieser Aufgabe sollen Sie die Klassen FridgeItem, Cheese und Yoghurt anpassen. Die Schnittstelle Weightful ist vorgegeben und darf nicht verändert werden.
Ergänzen Sie die Klasse FridgeItem wie folgt:
----- a) -----
Fügen Sie der Klasse 3 private Instanzvariablen hinzu: "weight" vom Typ double, "name" vom Typ String und "color" vom Typ String.
----- b) -----
Initialisieren Sie diese Felder im vorgegebenen Konstruktor mit den Werten, die dieser als Parameter erhält.
----- c) -----
Implementieren Sie die Schnittstelle Weightful und geben Sie in der zugehörigen Methode den Wert der Instanzvariable "weight" zurück.
----- d) -----
Überschreiben Sie die toString() Methode aus java.lang.Object, so dass diese eine Zeichenkette in folgendem Format zurückgibt: <name> (<color> <weight> g) (also: Wert der Instanzvariable name, Leerzeichen, Klammer auf, Wert der Instanzvariable color, Leerzeichen, Wert der Instanzvariable weight, Leerzeichen, kleines g, Klammer zu)
Ergänzen Sie die Klassen Cheese und Yoghurt wie folgt:
----- e) -----
Ändern Sie die Vererbungsbeziehungen so, dass beide Klassen von FridgeItem erben.
----- f) -----
Fügen Sie den Klassen den Konstruktor Ihrer neuen Superklasse hinzu und geben Sie die Parameter an die Superklasse weiter.
----- g) -----
Überschreiben Sie die toString() Methode, so dass vor den Wert der Implementierung aus der Superklasse noch der Name der Klasse gefolgt von einem Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu FridgeItem soll die Ausgabe wie folgt aussehen:
Cheese: <name> (<color> <weight> g) (für toString() in Cheese)
Yoghurt: <name> (<color> <weight> g) (für toString() in Yoghurt)
Nachdem Sie diese Änderungen gemacht haben, sollten alle Kompilierungsfehler beseitigt sein.
@@ -0,0 +1,19 @@
Aufgabe 1 - Der Kühlschrank - 50 Punkte
Diese Aufgabe baut auf der Aufgabe des vorherigen Testats auf. Bearbeiten Sie ausschließlich die Klasse Fridge.
Verändern Sie NICHT die Klassen Weightful, FridgeItem, Cheese und Yoghurt.
Die Klasse Fridge (Kühlschrank) speichert eine begrenzte Menge an FridgeItem (Gegenständen) mit Hilfe eines "item"-Arrays. Die containsItem-Methode prüft, ob sich ein Gegenstand bereits im Kühlschrank (d.h. im Array) befindet. Die addItem-Methode fügt einen Gegenstand hinzu, sofern dieser nicht null ist und es noch Platz gibt (also items.length < maxItems).
Erweitern Sie die Klasse wie folgt:
----- a) -----
Implementieren Sie die Schnittstelle Weightful und geben Sie über die getWeight-Methode die Summe der Gewichte aller Gegenstände im Kühlschrank zurück.
----- b) -----
Ergänzen Sie die Prüfungen in der addItem-Methode so dass diese zusätzlich noch sicherstellt, dass ein Gegenstand nur dann hinzugefügt wird.
– wenn er sich noch nicht im Kühlschrank befindet (Tipp: containsItem)
– wenn dadurch das maximale Gewicht (gespeichert in der Instanzvariable "maxWeight") nicht überschritten wird (Tipp: getWeight).
----- c) -----
Implementieren Sie die Methode indexOf(name,startIndex), sodass diese das FridgeItem mit dem Namen "name" im items-Array ab der Stelle "startIndex" bis "items.length - 1" sucht. Wird ein FridgeItem mit dem Namen gefunden, soll der kleinste Index zurückgegeben werden. Ist der Name nicht im Bereich von "startIndex" bis "items.length - 1" enthalten, soll -1 zurückgegeben werden. Einschränkung: Nutzen Sie für die Implementierung dieser Methode keinerlei Schleifen, sondern ausschließlich Rekursion.
@@ -0,0 +1,26 @@
Aufgabe 2 - Deque - 50 Punkte
Eine doppelt verkette Liste (Doubly linked list) funktioniert wie die aus der Vorlesung bekannte verkettete List (Linked list), der einzige Unterschied ist, dass jedes Element zu dem Verweis auf das nächste Element auch noch ein Verweis auf das vorherige Element hat.
Eine Deque (Double-ended queue) ist ähnlich zu einer Queue und einem Stack, sie kombiniert die Eigenschaften beider Datentypen. Der einzige Unterschied ist, dass Daten an beiden Enden gelesen, eingefügt und entfernt werden können.
In unserem Fall soll die Deque intern durch eine doppelt verkettete Liste repräsentiert werden.
Implementieren Sie die folgenden Methoden in der Klasse Deque:
----- a) -----
void addLast(String): Diese Methode soll den übergebenen String ans Ende der Deque anfügen.
Wenn der String null oder leer ist, soll nichts passieren.
----- b) -----
String peekFirst(): Diese Methode soll den ersten String der Deque zurückgeben OHNE diesen zu entfernen.
Falls die Deque leer ist, soll null zurückgegeben werden.
----- c) -----
String pollLast(): Diese Methode soll den letzten String der Deque entfernen UND zurückgeben.
Falls die Deque leer ist, soll null zurückgegeben werden.
----- d) -----
int size(): Diese Methode soll die aktuelle Anzahl der Strings in der Deque zurückgeben.
Verändern Sie NICHT die anderen Methoden der Klasse Deque.
@@ -0,0 +1,29 @@
Aufgabe 1 - Baum - 60 Punkte
Die Klasse Tree implementiert einen geordneten Binärbaum, der intern mit der Klasse TreeNode umgesetzt wird. Ein TreeNode besitzt hierfür einen double-Wert (value), sowie ein linkes Kind (left) und ein rechtes Kind (right). Die Klasse TreeVisitor speichert die Sequenz von TreeNodes, die über die visit-Methode an TreeVisitor übergeben werden.
Implementieren Sie die folgenden Methoden in der Klasse Tree:
----- a) -----
void traverse(TreeVisitor visitor, TreeNode current)
Diese Methode soll den Teilbaum mit der Wurzel "current" vollständig ablaufen (traversieren). Während der Traversierung, soll die Methode visit(TreeNode) am übergebenen Visitor in der Hauptreihenfolge (pre-order) aufgerufen werden (d.h. für jeden Teilbaum erst die Wurzel, dann den Teilbaum des linken Kinds und dann den Teilbaum des rechten Kinds).
Tipp: Falls Sie die Hauptreihenfolge (pre-order) nicht verstehen, implementieren Sie irgendeine vollständige Traversierung, um zumindest Teilpunkte zu erhalten.
----- b) -----
int count(double value, TreeNode current)
Diese Methode soll ausgehend von "current" die Anzahl der TreeNodes zählen, deren Wert dem übergebenen "value" entspricht. Die Implementierung der Methode soll dabei nur die Teilbäume weiterverfolgen, die den Wert auch enthalten können. Beachten Sie dazu die Ordnung, die die insert-Methode in der Klasse Tree definiert.
Tipp: Falls Ihnen die Umsetzung einer effizienten Implementierung nicht klar ist, missachten Sie diese Anforderung, um zumindest Teilpunkte zu erhalten.
----- c) -----
int height()
Diese Methode soll die Höhe des gesamten Baums berechnen und zurückgeben.
Die Höhe eines Baums ist wie folgt definiert:
- Ein leerer Baum hat die Höhe 0.
- Ein einzelner Knoten hat die Höhe 1.
- Allgemein ist die Höhe eines Baums 1 plus die maximale Höhe seiner Teilbäume.
@@ -0,0 +1,17 @@
Aufgabe 2 - I/O-Serialisierung von Listen - 20 Punkte
Implementieren Sie folgenden Methoden in der Klasse StringListSerializer:
----- a) -----
void write(Path path, List<String> list)
Diese Methode soll den Inhalt der übergebenen Liste in die Datei des übergebenen Pfades schreiben. Dabei soll ein Element der Liste, einer Zeile der Datei entsprechen.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
----- b) -----
List<String> read(Path path)
Diese Methode soll den Inhalt der Datei des übergebenen Pfades zurückgeben. Jedes Element der zurückgegebenen Liste soll einer Zeile der Datei entsprechen. Im Falle einer IOException, soll eine leere Liste zurückgegeben werden.
Nutzen Sie dafür AUSSCHLIEßLICH Methoden welche in der Klasse java.nio.file.Files vorhanden sind.
@@ -0,0 +1,20 @@
Aufgabe 3 - Deque Exceptions - 20 Punkte
Diese Aufgabe baut auf der Deque Aufgabe aus dem vorherigen Testat auf. In dieser Aufgabe sollen Sie die Methoden zum hinzufügen und zum erhalten von Werten anpassen.
----- a) -----
Passen Sie die Methoden addFirst und addList so an, dass diese eine Exception werfen, wenn der übergebene Wert null oder leer ist.
- Falls der übergebene Wert null ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be null" geworfen werden.
- Falls der übergebene Wert leer ist soll eine IllegalArgumentException mit der Nachricht "Value cannot be empty" geworfen werden.
----- b) -----
Passen Sie die Methoden getFirst und getLast so an, dass diese eine NoSuchElementException werfen, wenn die Deque leer ist (Tipp: isEmpty).
- Die Nachricht der Exception soll dabei "Deque is empty" sein.
Passen Sie bei allen Methoden die eine Exception schmeißen sollen die Signatur so an, dass diese auf die Art der möglichen Exception hinweisen.
Für die volle Punktzahl müssen die Nachrichten der Exception genau der in der Aufgabenstellung beschriebenen Nachricht entsprechen.
Passen Sie KEINE anderen Methoden in der Klasse an. Die Aufgabe ist mit allen vorliegenden Methoden lösbar.
@@ -0,0 +1,2 @@
Dieses Testat besteht aus der Schnittstelle Person sowie den Klassen Student, Operation, LinkedList, ListItem und Main. Die Schnittstelle Person und die Klasse ListItem sollen sie nicht verändern.
Die Klasse Main enthält eine main-Methode mit der Sie Ihre Implementierung testen können.
@@ -0,0 +1,9 @@
Aufgabe 1 – Klassen, Variablen und Methoden (40 Punkte)
Erweitern Sie die Klasse Student wie folgt:
- Fügen Sie der Klasse zwei private Instanzvariablen hinzu: "name" vom Typ String und "id" vom Typ long.
- Implementieren Sie die Schnittstelle Person, indem Sie den Inhalt der entsprechenden Instanzvariablen in den dafür vorgesehenen Methoden zurückgeben.
- Implementieren Sie einen öffentlichen Konstruktor mit einem Parameter "name" und einem Parameter "id" (in dieser Reihenfolge), der die Instanzvariablen mit dem selben Namen initialisiert.
- Überschreiben Sie die equals-Methode aus der Klasse java.lang.Object, sodass Studenten auf Basis ihrer "id" miteinander verglichen werden.
Wenn Sie mit dieser Aufgabe fertig sind, sollte die Klasse Main keine Compilerfehler mehr aufweisen.
@@ -0,0 +1,3 @@
Aufgabe 2 – Arrays und Exceptions (20 Punkte)
Implementieren Sie die Methode double average(double[] values) in der Klasse Operation, so dass diese den Durchschnitt der im Parameter "values" übergebenen Werte berechnet und zurückliefert. Enthält "values" keine Werte oder ist "values" null, soll Ihre Implementierung der average Methode eine java.lang.IllegalArgumentException auslösen.
@@ -0,0 +1,7 @@
Aufgabe 3 – Verkettete Listen (40 Punkte)
Die Klasse LinkedList soll eine einfach verkettete Liste darstellen. Implementieren Sie mit Hilfe der Definitionen in der Klasse ListItem die folgenden Methoden der Klasse LinkedList:
- int size(): Diese Methode soll die Anzahl der Elemente in der Liste zurückliefern.
- void prepend(String value): Diese Methode soll den übergebenen String "value" an den Anfang der Liste einfügen. Der bisherige Listeninhalt soll dabei natürlich erhalten bleiben und um eins nach hinten verschoben werden.
- String get(int i): Diese Methode soll den Wert des i-ten Elements in der Liste zurückgeben.
Falls i kein gültiger Verweis auf ein Element der Liste ist, soll von Ihrer Implementierung der Methode eine java.lang.IllegalArgumentException ausgelöst werden.
-30
View File
@@ -1,23 +1,5 @@
/**
* Aufgabe 3e
*
* Verändern Sie die Klasse Cheese so, dass sie von FridgeItem erbt.
*
* Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt.
*/
public class Cheese { // TODO: change
/**
* Aufgabe 3f
*
* Fügen Sie der Klasse Cheese einen Konstruktor hinzu, der die Variablen
* weight, name und color initialisiert. Geben Sie dafür die Werte an den
* Konstruktor der Superklasse weiter.
*
* Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt.
*/
/**
* Creates a new cheese with the weight, name and color.
*
@@ -27,18 +9,6 @@ public class Cheese { // TODO: change
*/
// TODO: constructor
/**
* Aufgabe 3g
*
* Überschreiben Sie die toString() Methode, so dass vor den Wert der
* Implementierung aus der Superklasse noch der Name der Klasse gefolgt von
* einem Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu
* FridgeItem soll die Ausgabe wie folgt aussehen:
*
* Cheese: <name> (<color> <weight> g)
*
* Nicht übersehen: Machen Sie dies auch für die Klasse Yoghurt.
*/
// TODO: toString
}
+3 -33
View File
@@ -1,21 +1,8 @@
/**
* Aufgabe 3c
*
* Implementieren Sie die Schittstelle Weightful und geben Sie in der
* dazugehörigen Methode den Wert der Instanzvariable weight zurück.
*
* Entfernen Sie auf KEINEN Fall TraceableItem.
* A class representing an item in a fridge.
*/
public abstract class FridgeItem extends TraceableItem { // TODO: change
/**
* Aufgabe 3a
*
* Fügen Sie unterhalb, drei Private Variablen für die
* Gewicht, Name und Farbe des Items hinzu. Dabei soll weight vom Typ double,
* name vom Typ String und color vom Typ String sein.
*/
public class FridgeItem { // TODO: change
/**
* The weight of the item.
@@ -32,13 +19,6 @@ public abstract class FridgeItem extends TraceableItem { // TODO: change
*/
// TODO: add variable
/**
* Aufgabe 3b
*
* Initalisieren Sie die vorher angelegten Variablen im vorgegebenen Konstruktor
* mit Werten, den dieser als Parameter erhält.
*/
/**
* Creates a fridge item with the specified weight, name and color.
*
@@ -48,7 +28,6 @@ public abstract class FridgeItem extends TraceableItem { // TODO: change
*/
public FridgeItem(double weight, String name, String color) {
// TODO: assign member variables
}
/**
@@ -69,15 +48,6 @@ public abstract class FridgeItem extends TraceableItem { // TODO: change
return color;
}
/**
* Aufgabe 3d
*
* Überschreiben Sie die toString() Methode aus java.lang.Object, so dass diese
* eine Zeichenkette in folgendem Format zurückgibt: <name> (<color> <weight> g)
* (also: Wert der Instanzvariable name, Leerzeichen, Klammer auf, Wert der
* Instanzvariable color, Leerzeichen, Wert der Instanzvariable weight,
* Leerzeichen, kleines g, Klammer zu)
*/
// TODO: toString
}
+2 -32
View File
@@ -1,21 +1,5 @@
import java.util.Arrays;
public class Testat1A {
/**
* Aufgabe 1
* Die folgende Methode soll für alle Werte des übergebenen Arrays arr, welche
* größer als der Grenzwert threshold sind, den Durchschnitt berechnen. Sollten
* keine Werte größer als der Grenzwert vorhanden sein, soll 0 zurückgegeben
* werden.
*
* HINWEISE:
* Beachten Sie, dass die Division durch 0 zu einem Fehler führt.
*
* Beachten Sie ebenfalls, dass der Array arr auch null sein kann oder leer ist.
* In diesem Fall soll 0 zurückgegeben werden.
*/
/**
* Returns the average of all values in the array that are above the given
* threshold.
@@ -27,23 +11,9 @@ public class Testat1A {
*/
public static double calculateMeanAbove(int[] arr, int threshold) {
// TODO: implement Aufgabe 1
return -42.0;
}
/**
* Aufgabe 2
* Die folgende Methode soll den Durchschnitt für jede Reihe in einem 2D-Array
* berechnen.
*
* HINWEISE:
* Beachten Sie, dass die Division durch 0 zu einem Fehler führt.
*
* Beachten Sie ebenfalls, dass das 2D-Array auch null oder leer sein kann. In
* diesem Fall soll ein leeres Array zurückgegeben werden. Außerdem kann es
* sein, dass eine Reihe null oder leer ist. In diesem Fall soll 0 für diese
* Reihe zurückgegeben werden.
*/
/**
* Returns the average of all rows in a 2D array.
*
@@ -52,6 +22,6 @@ public class Testat1A {
*/
public static double[] calculateRowMean(int[][] arr) {
// TODO: implement Aufgabe 2
return new double[42];
}
}
+37 -51
View File
@@ -5,6 +5,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Arrays;
@@ -153,7 +154,7 @@ public class Tests {
@Test(name = "Aufgabe 3a - private fields - 6 points")
public void testA3PrivateFields() {
int points = 9;
int points = 6;
points -= testField(FridgeItem.class, "weight", double.class, 2);
points -= testField(FridgeItem.class, "name", String.class, 2);
points -= testField(FridgeItem.class, "color", String.class, 2);
@@ -181,32 +182,33 @@ public class Tests {
int points = 8;
Class<?> clazz = FridgeItem.class;
if (!implementsInterface(clazz, Weightful.class)) {
TracingFramework.printError(String.format("FAIL: Class '%s' does not implement interface '%s'",
clazz.getName(), Weightful.class.getName()));
points = 0;
points -= 4;
TracingFramework
.printError(String.format("FAIL: Class '%s' does not implement interface '%s'. Deducting 4 points.",
clazz.getName(), Weightful.class.getName()));
}
Optional<Method> method = findMethod(FridgeItem.class, "getWeight", double.class);
if (method.isEmpty()) {
points -= 4;
TracingFramework
.printError(String.format("FAIL: Method 'getWeight' not found in class '%s'. Deducting 4 points.",
clazz.getName()));
} else {
Method getWeightMethod = method.get();
double weight = 42.314159;
FridgeItem item = new TestItem(weight, "Foo", "Red");
Method method = getMethod(clazz, "getWeight");
if (method == null || !method.getReturnType().equals(double.class)) {
TracingFramework.printError(
String.format("FAIL: Method 'getWeight' not found in class '%s' or has wrong return type",
clazz.getName()));
points = 0;
} else {
try {
double result = (double) method.invoke(item);
if (result != weight) {
TracingFramework.printError(String.format("FAIL: Expected getWeight() to return %f, but got %f",
weight, result));
points = 0;
}
} catch (IllegalAccessException | InvocationTargetException e) {
TracingFramework
.printError(String.format("FAIL: Could not invoke getWeight() on item of class '%s'",
item.getClass().getName()));
try {
double result = (double) getWeightMethod.invoke(item);
if (result != weight) {
TracingFramework.printError(String.format("FAIL: Expected getWeight() to return %f, but got %f",
weight, result));
points = 0;
}
} catch (IllegalAccessException | InvocationTargetException e) {
TracingFramework
.printError(String.format("FAIL: Could not invoke getWeight() on item of class '%s'",
item.getClass().getName()));
points = 0;
}
}
@@ -248,35 +250,6 @@ public class Tests {
TracingFramework.printError(String.format("FAIL: Could not create instance of class '%s'",
Cheese.class.getName()));
points = 0;
} else {
List<String> expectedTraceExcerpt = List.of("TraceableItem", "FridgeItem", "Cheese");
Method method = getMethod(Cheese.class, "getTrace");
if (method == null) {
TracingFramework.printError(String.format("FAIL: Method 'getTrace' not found in class '%s'",
Cheese.class.getName()));
points -= 5;
} else {
try {
Object rawTrace = method.invoke(cheese);
List<?> rawList = (List<?>) rawTrace;
List<String> classTrace = rawList.stream()
.filter(StackTraceElement.class::isInstance)
.map(StackTraceElement.class::cast)
.map(StackTraceElement::getClassName)
.collect(Collectors.toList());
int index = Collections.indexOfSubList(classTrace, expectedTraceExcerpt);
if (index == -1) {
TracingFramework.printError(
String.format(
"FAIL: Cheese does not call super constructor. Creation class trace: %s",
classTrace));
points -= 2;
}
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@@ -403,6 +376,19 @@ public class Tests {
}
}
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?> returnType,
Class<?>... parameterTypes) {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
if (method.getReturnType().equals(returnType)) {
return Optional.of(method);
}
} catch (NoSuchMethodException e) {
// Method not found
}
return Optional.empty();
}
/**
* Returns true if the class clazz extends the superclass superclass.
*
-16
View File
@@ -1,16 +0,0 @@
import java.util.ArrayList;
import java.util.List;
public class TraceableItem {
private List<StackTraceElement> traceElements = new ArrayList<>();
public TraceableItem() {
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
traceElements.add(ste);
}
}
public List<StackTraceElement> getTrace() {
return traceElements;
}
}
-30
View File
@@ -1,23 +1,5 @@
/**
* Aufgabe 3e
*
* Verändern Sie die Klasse Yoghurt so, dass sie von FridgeItem erbt.
*
* HINWEIS: Machen Sie dies auch für die Klasse Cheese.
*/
public class Yoghurt { // TODO: change
/**
* Aufgabe 3f
*
* Fügen Sie der Klasse Yoghurt einen Konstruktor hinzu, der die Variablen
* weight, name und color initialisiert. Geben Sie dafür die Werte an den
* Konstruktor der Superklasse weiter.
*
* Nicht übersehen: Machen Sie dies auch für die Klasse Cheese.
*/
/**
* Creates a new yoghurt with the weight, name and color.
*
@@ -27,18 +9,6 @@ public class Yoghurt { // TODO: change
*/
// TODO: constructor
/**
* Aufgabe 3g
*
* Überschreiben Sie die toString() Methode, so dass vor den Wert der
* Implementierung aus der Superklasse noch der Name der Klasse gefolgt von
* einem Doppelpunkt und einem Leerzeichen angefügt wird. D.h. analog zu
* FridgeItem soll die Ausgabe wie folgt aussehen:
*
* Yoghurt: <name> (<color> <weight> g)
*
* Nicht übersehen: Machen Sie dies auch für die Klasse Cheese.
*/
// TODO: toString
}
+18
View File
@@ -0,0 +1,18 @@
public class Cheese extends FridgeItem {
/**
* Creates a new cheese with the weight, name and color.
*
* @param weight The weight.
* @param name The name.
* @param color The color.
*/
public Cheese(double weight, String name, String color) {
super(weight, name, color);
}
@Override
public String toString() {
return "Cheese: " + super.toString();
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Represents a double-ended queue (deque) that allows adding and removing items
* from both ends.
*/
public class Deque {
/**
* The front item of the deque.
*/
private Item front;
/**
* The back item of the deque.
*/
private Item back;
/**
* Constructs an empty deque.
*/
public Deque() {
this.front = null;
this.back = null;
}
/**
* Returns the front item in the deque.
*
* @return The front item in the deque.
*/
private Item getFront() {
return front;
}
/**
* Returns the back item in the deque.
*
* @return The back item in the deque.
*/
private Item getBack() {
return back;
}
/**
* Sets the front item in the deque.
*
* @param front The item to set as the front.
*/
private void setFront(Item front) {
this.front = front;
}
/**
* Sets the back item in the deque.
*
* @param back The item to set as the back.
*/
private void setBack(Item back) {
this.back = back;
}
/**
* Adds an item to the front of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addFirst(String value) {
if (value == null || value.isEmpty()) {
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
} else {
item.setNext(getFront());
getFront().setPrev(item);
setFront(item);
}
}
/**
* Adds an item to the back of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addLast(String value) {
// TODO: implement this method
}
/**
* Returns the value of the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the front item in the deque, or null if the deque is
* empty.
*/
public String peekFirst() {
// TODO: implement this method
return "Not implemented yet";
}
/**
* Returns the value of the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the back item in the deque, or null if the deque is
* empty.
*/
public String peekLast() {
if (isEmpty()) {
return null;
} else {
return getBack().getValue();
}
}
/**
* Removes and returns the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed front item, or null if the deque is empty.
*/
public String pollFirst() {
if (isEmpty()) {
return null;
} else {
String value = getFront().getValue();
setFront(getFront().getNext());
if (getFront() == null) {
setBack(null);
}
return value;
}
}
/**
* Removes and returns the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed back item, or null if the deque is empty.
*/
public String pollLast() {
// TODO: implement this method
return "Not implemented yet";
}
/**
* Returns the number of items in the deque.
*
* @return The number of items in the deque.
*/
public int size() {
// TODO: implement this method
return -42;
}
/**
* Checks if the deque is empty.
*
* @return true if the deque is empty, false otherwise.
*/
public boolean isEmpty() {
return getFront() == null && getBack() == null;
}
/**
* Returns a string representation of the deque.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Item current = getFront();
sb.append("[");
while (current != null) {
sb.append(current.getValue());
current = current.getNext();
if (current != null) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
+145
View File
@@ -0,0 +1,145 @@
public class Fridge { // TODO: change
/**
* The current items in the fridge.
*/
private FridgeItem[] items = new FridgeItem[0];
/**
* The maximum items to place in the fridge.
*/
private int maxItems;
/**
* The maximum weight of the items in the fridge.
* The sum of the weights of the items in the
* fridge must not be higher than this.
*/
private double maxWeight;
/**
* Creates a fridge that can support the specified
* number of items with the specified total
* maximum weight.
*
* @param maxItems The maximum number of items that
* the fridge can hold.
* @param maxWeight The total maximum weight that
* the current items in the fridge may have.
*/
public Fridge(int maxItems, double maxWeight) {
this.maxItems = maxItems;
this.maxWeight = maxWeight;
}
/**
* Determines whether an item is in the fridge.
*
* @param item The item to check.
* @return True if it is in the fridge, false otherwise.
*/
public boolean containsItem(FridgeItem item) {
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
return true;
}
}
return false;
}
/**
* Adds a non-null item that is not in the fridge to
* the fridge unless there is no more space.
*
* @param item The item to add.
* @return True if the item has been added, false if
* the item is null or if there is no more space or
* if the item is already in the fridge.
*/
public boolean addItem(FridgeItem item) { // TODO: add more checks
// check invalid states
if (item == null) { // Cannot add null item, sorry
return false;
}
if (items.length == maxItems) { // Cannot add more items to the fridge
return false;
}
// all checks ok, add the item
FridgeItem[] newItems = new FridgeItem[items.length + 1];
for (int j = 0; j < items.length; j++) {
newItems[j] = items[j];
}
newItems[items.length] = item;
items = newItems;
return true;
}
/**
* Recursively searches an item with a specified name in
* the item array (from startIndex to items.length - 1)
* and if present, returns the lowest index of such an item.
* If no such item exists, the method returns -1.
*
* @param name The name of the item to search.
* @param startIndex The index to start from (0 <= startIndex < items.length).
* @return If found, the index of the first item in the items
* array with the specified name when starting to search from
* startIndex to items.length - 1. If no such item exists, the
* method returns -1.
*/
public int indexOf(String name, int startIndex) {
// TODO: implement
return -42;
}
// Other helper methods, not needed for this task.
/**
* Removes an item from the fridge and returns if something
* has actually been removed.
*
* @param item The item to remove.
* @return True if the item was removed, false if the item was
* not in the fridge.
*/
public boolean removeItem(FridgeItem item) {
// search for the item on the fridge
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
// if found, create a copy of the items without it
FridgeItem[] newItems = new FridgeItem[items.length - 1];
for (int j = 0; j < newItems.length; j++) {
if (j < i) {
newItems[j] = items[i];
} else {
newItems[j] = items[i + 1];
}
}
// and replace the old items with the new ones
items = newItems;
return true;
}
}
return false;
}
/**
* Returns a string representation of the fridge.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.length; i++) {
sb.append(items[i].toString());
if (i < items.length - 1) {
sb.append(", ");
}
}
if (this instanceof Weightful weightful) {
sb.append("Weight: " + weightful.getWeight() + " kg");
}
return sb.toString();
}
}
+59
View File
@@ -0,0 +1,59 @@
public class FridgeItem implements Weightful {
/**
* The weight of the item.
*/
private double weight;
/**
* The name of the item.
*/
private String name;
/**
* The color of the item.
*/
private String color;
/**
* Creates a fridge item with the specified weight, name and color.
*
* @param weight The weight of the item.
* @param name The name of the item.
* @param color The color of the item.
*/
public FridgeItem(double weight, String name, String color) {
this.weight = weight;
this.name = name;
this.color = color;
}
/**
* Returns the name of the item.
*
* @return The name of the item.
*/
public String getName() {
return name;
}
/**
* Returns the color of the item.
*
* @return The color of the item.
*/
public String getColor() {
return color;
}
@Override
public double getWeight() {
return weight;
}
@Override
public String toString() {
return name + " (" + color + " " + weight + " g)";
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Represents an item in a doubly linked deque.
*/
public class Item {
/**
* The value of the item.
*/
private String value;
/**
* The previous item in the deque.
*/
private Item prev;
/**
* The next item in the deque.
*/
private Item next;
/**
* Constructor for creating a new item.
*
* @param value The value of the item.
*/
public Item(String value) {
this.value = value;
this.prev = null;
this.next = null;
}
/**
* Returns the value of the item.
*
* @return The value of the item.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the item.
*
* @param value The value of the item.
*/
public void setValue(String value) {
this.value = value;
}
/**
* Returns the previous item in the deque.
*
* @return The previous item in the deque.
*/
public Item getPrev() {
return prev;
}
/**
* Sets the previous item in the deque.
*
* @param prev The previous item in the deque.
*/
public void setPrev(Item prev) {
this.prev = prev;
}
/**
* Returns the next item in the deque.
*
* @return The next item in the deque.
*/
public Item getNext() {
return next;
}
/**
* Sets the next item in the deque.
*
* @param next The next item in the deque.
*/
public void setNext(Item next) {
this.next = next;
}
}
+204
View File
@@ -0,0 +1,204 @@
public class Main {
/**
* Die folgende main-Methode dient Ihnen zur Hilfe, um Ihre Lösungen zu testen.
* Beachten Sie bitte, dass in dieser Methode nicht alle Tests enthalten sind,
* sondern nur einige, die Ihnen helfen sollen, Ihre Lösungen zu überprüfen.
*/
public static void main(String[] args) {
System.out.println("Aufgabe 1: Fridge");
System.out.println("");
// create items
FridgeItem gouda = new Cheese(500.5, "Gouda", "yellow");
FridgeItem cheddar = new Cheese(1123.75, "Cheddar", "orange");
FridgeItem cherryYoghurt = new Yoghurt(250, "Cherry", "red");
FridgeItem vanillaYoghurt = new Yoghurt(500, "Vanilla", "light yellow");
// create fridge
Fridge fridge = new Fridge(4, 2000.0);
fridge.addItem(cheddar);
fridge.addItem(gouda);
// Aufgabe 1 - addItem
System.out.println("Testing Fridge.addItem()");
boolean addCheddarAgain = fridge.addItem(cheddar);
if (addCheddarAgain) {
System.out.println("Failure: The cheddar should not be added twice.");
} else {
System.out.println("Success: The cheddar was not added again.");
}
boolean addGouda = fridge.addItem(gouda);
if (addGouda) {
System.out.println("Failure: The gouda should be too heavy.");
} else {
System.out.println("Success: The gouda is too heavy.");
}
if (fridge.containsItem(gouda)) {
System.out.println("Failure: The gouda should not be added.");
} else {
System.out.println("Success: The fridge does not contain the gouda.");
}
boolean addCherryYoghurt = fridge.addItem(cherryYoghurt);
if (addCherryYoghurt) {
System.out.println("Success: The cherry yoghurt fits in the fridge.");
} else {
System.out.println("Failure: The cherry yoghurt should fit in the fridge.");
}
if (fridge.containsItem(cherryYoghurt)) {
System.out.println("Success: The fridge contains the cherry yoghurt.");
} else {
System.out.println("Failure: The fridge does not contain the cherry yoghurt.");
}
System.out.println();
// Aufgabe 1 - indexOf
System.out.println("Testing: Fridge.indexOf()");
System.out.println("Fridge.indexOf(cheddar.getName(), 0) Expected: 0, Your code: "
+ fridge.indexOf(cheddar.getName(), 0));
System.out.println("Fridge.indexOf(cheddar.getName(), 1) Expected: -1, Your code: "
+ fridge.indexOf(cheddar.getName(), 1));
System.out.println("Fridge.indexOf(cheddar.getName(), 2) Expected: -1, Your code: "
+ fridge.indexOf(cheddar.getName(), 2));
System.out.println("Fridge.indexOf(cherryYoghurt.getName(), 0) Expected: 2, Your code: "
+ fridge.indexOf(cherryYoghurt.getName(), 0));
fridge.addItem(new Yoghurt(50.5, "Cherry", "red")); // add same name to check ordering
System.out.println("Fridge.indexOf(cherryYoghurt.getName(), 0) Expected: 2, Your code: "
+ fridge.indexOf(cherryYoghurt.getName(), 0));
System.out.println("");
System.out.println("Aufgabe 2: Deque");
System.out.println("");
// create a deque
Deque deque = new Deque();
// add first item to the deque
deque.addLast("Item 1");
// deque should now contain: ["Item 1"]
System.out.println(deque);
System.out.println("-> Should contain: [Item 1]");
// deque size should be 1
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 1");
// deque should not be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be false");
// peek first should return "Item 1"
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return 'Item 1'");
// peek last should return "Item 1"
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return 'Item 1'");
System.out.println("");
// add second item to the deque
deque.addLast("Item 2");
// deque should now contain: ["Item 1", "Item 2"]
System.out.println(deque);
System.out.println("-> Should contain: [Item 1, Item 2]");
// deque size should be 2
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 2");
// deque should not be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be false");
// peek first should return "Item 1"
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return 'Item 1'");
// peek last should return "Item 2"
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return 'Item 2'");
System.out.println("");
// add third item to the deque
deque.addLast("Item 3");
// deque should now contain: ["Item 1", "Item 2", "Item 3"]
System.out.println(deque);
System.out.println("-> Should contain: [Item 1, Item 2, Item 3]");
// deque size should be 3
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 3");
// deque should not be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be false");
// peek first should return "Item 1"
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return 'Item 1'");
// peek last should return "Item 3"
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return 'Item 3'");
System.out.println("");
// poll last should return "Item 3" and remove it from the deque
System.out.println("Poll last: " + deque.pollLast());
System.out.println("-> Should return 'Item 3'");
// deque should now contain: ["Item 1", "Item 2"]
System.out.println(deque);
System.out.println("-> Should contain: [Item 1, Item 2]");
// deque size should be 2
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 2");
// deque should not be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be false");
// peek first should return "Item 1"
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return 'Item 1'");
// peek last should return "Item 2"
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return 'Item 2'");
System.out.println("");
// poll last should return "Item 2" and remove it from the deque
System.out.println("Poll last: " + deque.pollLast());
System.out.println("-> Should return 'Item 2'");
// deque should now contain: ["Item 1"]
System.out.println(deque);
// deque size should be 1
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 1");
// deque should not be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be false");
// peek first should return "Item 1"
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return 'Item 1'");
// peek last should return "Item 1"
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return 'Item 1'");
System.out.println("");
// poll last should return "Item 1" and remove it from the deque
System.out.println("Poll last: " + deque.pollLast());
System.out.println("-> Should return 'Item 1'");
// deque should now be empty
System.out.println(deque);
System.out.println("-> Should be empty");
// deque size should be 0
System.out.println("Deque size: " + deque.size());
System.out.println("-> Should be size 0");
// deque should be empty
System.out.println("Is deque empty? " + deque.isEmpty());
System.out.println("-> Should be true");
// peek first should return null
System.out.println("Peek first: " + deque.peekFirst());
System.out.println("-> Peek first should return null");
// peek last should return null
System.out.println("Peek last: " + deque.peekLast());
System.out.println("-> Peek last should return null");
System.out.println("");
// poll last should return null since the deque is empty
System.out.println("Poll last: " + deque.pollLast());
System.out.println("-> Should return null since the deque is empty");
}
}
+616
View File
@@ -0,0 +1,616 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
public static void main(String[] args) {
Class<Tests> clazz = Tests.class;
Tests test = new Tests();
System.out.println(String.format("Tests: %s", test.getClass().getName()));
System.out.println();
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
System.out.println(String.format("Currently testing: %s", method.getName()));
int size = test.testPoints.size();
try {
method.invoke(test);
if (test.testPoints.size() != size + 1) {
System.err.println("ERROR: Test yields no or multiple results. Erroneous test.");
} else {
System.out.println(
String.format("PASS: Test passed with %d points!",
test.testPoints.get(test.testPoints.size() - 1)));
}
} catch (Exception e) {
System.err.println(String.format("ERROR: Test failed with exception: %s", e.getMessage()));
e.printStackTrace();
}
System.out.println();
}
}
System.out.println();
System.out.println(String.format("Total points: %d", test.getResult()));
}
@Test(name = "Aufgabe 1 - Fridge - getWeight - 10 Punkte")
public void testFridgeWeightful() {
int points = 10;
if (!implementsInterface(Fridge.class, Weightful.class)) {
points -= 5;
TracingFramework
.printError("Fridge should implement interface Weightful, but does not. Deducting 5 points.");
}
Optional<Method> method = findMethod(Fridge.class, "getWeight", double.class);
if (method.isEmpty()) {
points -= 5;
TracingFramework.printError(
"Fridge should implement method getWeight with return type double, but does not. Deducting 5 points.");
} else {
Method getWeight = method.get();
Fridge fridge = new Fridge(10, 500);
fridge.addItem(new Cheese(100, "A", "B"));
fridge.addItem(new Cheese(100, "C", "D"));
fridge.addItem(new Cheese(100, "E", "F"));
try {
double weight = (double) getWeight.invoke(fridge);
if (weight != 300.0) {
points -= 3;
TracingFramework.printError(
"A fridge with 3 x 100 g should have a weight of 300 g but was " + weight);
}
} catch (IllegalAccessException | InvocationTargetException e) {
points -= 3;
TracingFramework.printError("Error invoking getWeight method: " + e.getMessage());
}
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Fridge - addItem - 15 Punkte")
public void testFridgeAddItem() {
int points = 15;
// initialize fridge and items
Fridge fridge = new Fridge(10, 10);
Cheese a = new Cheese(1, "A", "B");
FridgeItem[] items = new FridgeItem[] {
a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D")
};
setItems(fridge, items);
// test for duplicates
// should return false and not add the item
boolean duplicates = fridge.addItem(a);
if (getItems(fridge).length == 3) {
if (duplicates) {
points -= 2;
TracingFramework.printError("Note: The fridge should return false for duplicates.");
}
} else {
points -= 4;
TracingFramework.printError("The fridge does not check for duplicates.");
}
// test for weight exceeding
// should return false and not add the item
setItems(fridge, new FridgeItem[] { a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D") });
boolean weight = fridge.addItem(new Cheese(8, "D", "E"));
if (getItems(fridge).length == 3) {
if (weight) {
points -= 2;
TracingFramework.printError("Note: The fridge should return false for exceeded weight.");
}
} else {
points -= 4;
TracingFramework.printError("The fridge does not check the weight.");
}
// max weight not actually exceeded
setItems(fridge, new FridgeItem[] { a, new Cheese(1, "B", "C"), new Cheese(1, "C", "D") });
boolean weight2 = fridge.addItem(new Cheese(7, "G", "H"));
if (getItems(fridge).length == 3) {
points -= 2;
TracingFramework
.printError("Note: The fridge doesn't add an item when it hits exactly the maximum weight.");
}
addPoints(points);
}
private static TraceableFridge createTraceableFridge() {
TraceableFridge fridge = new TraceableFridge(10, 10);
fridge.addItem(new Cheese(1, "A", "B"));
fridge.addItem(new Cheese(1, "B", "C"));
fridge.addItem(new Cheese(1, "C", "D"));
fridge.addItem(new Cheese(1, "A", "B"));
fridge.addItem(new Cheese(1, "B", "C"));
fridge.addItem(new Cheese(1, "C", "D"));
fridge.addItem(new Cheese(1, "A", "B"));
fridge.addItem(new Cheese(1, "B", "C"));
fridge.addItem(new Cheese(1, "C", "D"));
return fridge;
}
private static long countRecursionSteps(TraceableFridge fridge) {
List<StackTraceElement> stackTrace = fridge.getStackTrace();
return stackTrace.stream()
.filter(element -> element.getClassName().equals("Fridge") && element.getMethodName().equals("indexOf"))
.count();
}
@Test(name = "Aufgabe 1 - Fridge - indexOf - not existing item - 10 Punkte")
public void testFridgeIndexOfNotExisting() {
int points = 10;
TraceableFridge fridge = createTraceableFridge();
// test for not existing item
int index = fridge.indexOf("D", 0);
long recursionSteps = countRecursionSteps(fridge);
if (recursionSteps == 0) {
points -= 10;
TracingFramework.printError("The fridge should use recursion to find the index of an item.");
} else if (index != -1) {
points -= 10;
TracingFramework.printError("The fridge should return -1 for not existing items.");
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Fridge - indexOf - existing item - 5 Punkte")
public void testFridgeIndexOfExisting() {
int points = 5;
TraceableFridge fridge = createTraceableFridge();
// test for existing item
int index = fridge.indexOf("C", 0);
long recursionSteps = countRecursionSteps(fridge);
if (recursionSteps == 0) {
points -= 5;
TracingFramework
.printError("The fridge should use recursion to find the index of an item. Deducting 10 points.");
} else if (index != 2) {
points -= 5;
TracingFramework.printError(
"The fridge should return the index of the first occurrence of an item. Deducting 10 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Fridge - indexOf - shifted start - 10 Punkte")
public void testFridgeIndexOfShiftedStart() {
int points = 10;
TraceableFridge fridge = createTraceableFridge();
// test for shifted start
int index = fridge.indexOf("A", 1);
long recursionSteps = countRecursionSteps(fridge);
if (recursionSteps == 0) {
points -= 10;
TracingFramework
.printError("The fridge should use recursion to find the index of an item. Deducting 10 points.");
} else if (index != 3) {
points -= 10;
TracingFramework.printError(
"The fridge should return the index of the first occurrence of an item after start index. Deducting 10 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - addLast - valid values - 10 Punkte")
public void testDequeAddLast() {
int points = 10;
Deque deque = new Deque();
String[] values = { "A", "B", "C", "D", "E" };
for (String value : values) {
deque.addLast(value);
String lastValue = peekLast(deque);
if (!value.equals(lastValue)) {
String lastValueFromFront = peekLastFromFront(deque);
if (value.equals(lastValueFromFront)) {
points -= 1;
TracingFramework.printError(
"The pointers inside the deque are not set correctly, but the last value is still added properly. Deducting 1 point.");
} else {
points -= 2;
TracingFramework.printError(
"The last value is not added properly. Expected: " + value + ", but got: " + lastValue);
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - addLast - null or empty values - 5 Punkte")
public void testDequeAddLastNullOrEmpty() {
int points = 5;
Deque deque = new Deque();
deque.addLast(null);
if (getFront(deque) != null || getBack(deque) != null) {
points -= 3;
TracingFramework.printError("The deque should not add null values. Deducting 3 points.");
}
// setting back to empty deque
deque = new Deque();
deque.addLast("");
if (getFront(deque) != null || getBack(deque) != null) {
points -= 2;
TracingFramework.printError("The deque should not add empty values. Deducting 2 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - peekFirst - filled deque - 10 Punkte")
public void testDequePeekFirstFilled() {
int points = 10;
Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten");
String beforeStudentPeek = peekFirst(deque);
String firstValue = deque.peekFirst();
if (!"Das".equals(firstValue)) {
points -= 5;
TracingFramework
.printError("The first value should be 'Das', but got: " + firstValue + ". Deducting 5 points.");
}
String afterStudentPeek = peekFirst(deque);
if (!beforeStudentPeek.equals(afterStudentPeek)) {
points -= 5;
TracingFramework.printError("The peekFirst method should not change the deque. Deducting 5 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - peekFirst - empty deque - 5 Punkte")
public void testDequePeekFirstEmpty() {
int points = 5;
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.peekFirst();
if (value == null) {
points -= 5;
TracingFramework.printError(
"The peekFirst method returns null for an non empty deque, assuming it always returns null. Deducting 5 points.");
} else {
// empty the deque
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
value = deque.peekFirst();
if (value != null) {
points -= 5;
TracingFramework
.printError("The peekFirst method should return null for an empty deque. Deducting 5 points.");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - pollLast - filled deque - 10 Punkte")
public void testDequePollLastFilled() {
int points = 10;
Deque deque = buildDeque("Das", "kann", "man", "nicht", "raten");
String value = deque.pollLast();
if (!"raten".equals(value)) {
points -= 5;
TracingFramework.printError(
"The pollLast method should return 'raten', but got: " + value + ". Deducting 5 points.");
}
value = deque.pollLast();
if (!"nicht".equals(value)) {
points -= 5;
TracingFramework.printError("The pollLast method should return 'nicht', but got: " + value
+ ". Polling should remove the last item. Deducting 5 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - pollLast - empty deque - 5 Punkte")
public void testDequePollLastEmpty() {
int points = 5;
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.pollLast();
if (value == null) {
points -= 5;
TracingFramework.printError(
"The pollLast method returns null for an non empty deque, assuming it always returns null. Deducting 5 points.");
} else {
// empty the deque
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
value = deque.pollLast();
if (value != null) {
points -= 5;
TracingFramework
.printError("The pollLast method should return null for an empty deque. Deducting 5 points.");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - size - filled deque - 3 Punkte")
public void testDequeSizeFilled() {
int points = 3;
Deque deque = buildDeque("A", "B", "C", "D", "E");
int size = deque.size();
if (size != 5) {
points -= 3;
TracingFramework.printError("The size method should return 5, but got: " + size + ". Deducting 3 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - size - empty deque - 2 Punkte")
public void testDequeSizeEmpty() {
int points = 2;
Deque deque = buildDeque("A", "B", "C", "D", "E");
int size = deque.size();
if (size == 0) {
points -= 2;
TracingFramework.printError("The size method should not return 0 for a non-empty deque, but got: " + size
+ ". Assuming it always returns 0. Deducting 2 points.");
} else {
// empty the deque
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
size = deque.size();
if (size != 0) {
points -= 2;
TracingFramework.printError("The size method should return 0 for an empty deque, but got: " + size
+ ". Deducting 2 points.");
}
}
addPoints(points);
}
private Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
addLast(deque, value);
}
return deque;
}
private String pollFirst(Deque deque) {
Item first = getFront(deque);
if (first == null) {
return null;
}
String value = first.getValue();
if (first.getNext() != null) {
setFront(deque, first.getNext());
first.getNext().setPrev(null);
} else {
setFront(deque, null);
setBack(deque, null);
}
return value;
}
private String peekFirst(Deque deque) {
Item first = getFront(deque);
return first != null ? first.getValue() : null;
}
private String peekLast(Deque deque) {
Item last = getBack(deque);
return last != null ? last.getValue() : null;
}
private String peekLastFromFront(Deque deque) {
Item last = getLastFromFront(deque);
return last != null ? last.getValue() : null;
}
private Item getLastFromFront(Deque deque) {
Item current = getFront(deque);
while (current != null && current.getNext() != null) {
current = current.getNext();
}
return current;
}
private void addLast(Deque deque, String value) {
Item item = new Item(value);
if (isEmpty(deque)) {
setFront(deque, item);
setBack(deque, item);
} else {
Item back = getBack(deque);
back.setNext(item);
item.setPrev(back);
setBack(deque, item);
}
}
private boolean isEmpty(Deque deque) {
return getFront(deque) == null && getBack(deque) == null;
}
private Item getFront(Deque deque) {
try {
Method method = Deque.class.getDeclaredMethod("getFront");
method.setAccessible(true);
return (Item) method.invoke(deque);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Error accessing getFront method", e);
}
}
private Item getBack(Deque deque) {
try {
Method method = Deque.class.getDeclaredMethod("getBack");
method.setAccessible(true);
return (Item) method.invoke(deque);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
}
private void setFront(Deque deque, Item front) {
try {
Method method = Deque.class.getDeclaredMethod("setFront", Item.class);
method.setAccessible(true);
method.invoke(deque, front);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Error accessing setFront method", e);
}
}
private void setBack(Deque deque, Item back) {
try {
Method method = Deque.class.getDeclaredMethod("setBack", Item.class);
method.setAccessible(true);
method.invoke(deque, back);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Error accessing setBack method", e);
}
}
/**
* Sets the fridge items.
*
* @param fridge The fridge.
* @param items The items.
*/
private void setItems(Fridge fridge, FridgeItem[] items) {
try {
Field f = Fridge.class.getDeclaredField("items");
f.setAccessible(true);
f.set(fridge, items);
} catch (Exception e) {
TracingFramework.printError("Cannot set fridge items (" + e + ").");
}
}
/**
* The points of each test case.
*/
private List<Integer> testPoints = new ArrayList<>();
/**
* This method will be called by jack after all
* test have been executed to get the resulting
* points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : testPoints) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes
* that the method is called <b>exactly</b> once
* per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
testPoints.add(value);
}
public static boolean hasVariableOfType(Class<?> clazz, String fieldName, Class<?> fieldType) {
try {
Field field = clazz.getDeclaredField(fieldName);
return field.getType().equals(fieldType);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return false;
}
public static boolean hasPrivateVariable(Class<?> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
return Modifier.isPrivate(field.getModifiers());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return false;
}
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?> returnType,
Class<?>... parameterTypes) {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
if (method.getReturnType().equals(returnType)) {
return Optional.of(method);
}
} catch (NoSuchMethodException e) {
// Method not found
}
return Optional.empty();
}
public static boolean implementsInterface(Class<?> clazz, Class<?> interfaceClass) {
Class<?>[] interfaces = clazz.getInterfaces();
return Arrays.stream(interfaces).anyMatch(interfaceClass::equals);
}
public static boolean extendsClass(Class<?> clazz, Class<?> superclass) {
Class<?> currentSuperclass = clazz.getSuperclass();
while (currentSuperclass != null) {
if (currentSuperclass.equals(superclass)) {
return true;
}
currentSuperclass = currentSuperclass.getSuperclass();
}
return false;
}
/**
* Returns the fridge items via reflection.
*
* @param fridge The fridge.
* @return The fridge's items.
*/
private FridgeItem[] getItems(Fridge fridge) {
try {
Field f = Fridge.class.getDeclaredField("items");
f.setAccessible(true);
return (FridgeItem[]) f.get(fridge);
} catch (Exception e) {
TracingFramework.printError("Cannot get fridge items (" + e + ").");
return new FridgeItem[0];
}
}
}
+23
View File
@@ -0,0 +1,23 @@
import java.util.ArrayList;
import java.util.List;
public class TraceableFridge extends Fridge {
private List<StackTraceElement> stackTrace = new ArrayList<>();
public TraceableFridge(int maxItems, double maxWeight) {
super(maxItems, maxWeight);
}
public List<StackTraceElement> getStackTrace() {
return stackTrace;
}
@Override
public int indexOf(String name, int startIndex) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
this.stackTrace = List.of(stackTrace);
return super.indexOf(name, startIndex);
}
}
+10
View File
@@ -0,0 +1,10 @@
public interface Weightful {
/**
* The weight of the object.
*
* @return The weight of the object.
*/
double getWeight();
}
+20
View File
@@ -0,0 +1,20 @@
public class Yoghurt extends FridgeItem {
/**
* Creates a new yoghurt with the weight, name and color.
*
* @param weight The weight.
* @param name The name.
* @param color The color.
*/
public Yoghurt(double weight, String name, String color) {
super(weight, name, color);
}
@Override
public String toString() {
return "Yoghurt: " + super.toString();
}
}
@@ -0,0 +1,19 @@
package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TracingFramework {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Test {
String name();
}
public static void printError(String string) {
System.err.println("ERROR: " + string);
}
}
+253
View File
@@ -0,0 +1,253 @@
import java.util.NoSuchElementException;
/**
* Represents a double-ended queue (deque) that allows adding and removing items
* from both ends.
*/
public class Deque {
/**
* The front item of the deque.
*/
private Item front;
/**
* The back item of the deque.
*/
private Item back;
/**
* Constructs an empty deque.
*/
public Deque() {
this.front = null;
this.back = null;
}
/**
* Returns the front item in the deque.
*
* @return The front item in the deque.
*/
private Item getFront() {
return front;
}
/**
* Returns the back item in the deque.
*
* @return The back item in the deque.
*/
private Item getBack() {
return back;
}
/**
* Sets the front item in the deque.
*
* @param front The item to set as the front.
*/
private void setFront(Item front) {
this.front = front;
}
/**
* Sets the back item in the deque.
*
* @param back The item to set as the back.
*/
private void setBack(Item back) {
this.back = back;
}
/**
* Adds an item to the front of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addFirst(String value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
} else {
item.setNext(getFront());
getFront().setPrev(item);
setFront(item);
}
}
/**
* Adds an item to the back of the deque, if the value is not null or empty.
*
* @param value The value of the item to add.
*/
public void addLast(String value) { // TODO: change
if (value == null) {
// TODO: change
return;
}
if (value.isEmpty()) {
// TODO: change
return;
}
Item item = new Item(value);
if (isEmpty()) {
setFront(item);
setBack(item);
} else {
item.setPrev(getBack());
getBack().setNext(item);
setBack(item);
}
}
/**
* Returns the value of the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the front item in the deque, or null if the deque is
* empty.
*/
public String peekFirst() {
if (isEmpty()) {
return null;
} else {
return getFront().getValue();
}
}
/**
* Returns the value of the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the back item in the deque, or null if the deque is
* empty.
*/
public String peekLast() {
if (isEmpty()) {
return null;
} else {
return getBack().getValue();
}
}
/**
* Removes and returns the front item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed front item, or null if the deque is empty.
*/
public String pollFirst() {
if (isEmpty()) {
return null;
} else {
String value = getFront().getValue();
setFront(getFront().getNext());
if (getFront() == null) {
setBack(null);
}
return value;
}
}
/**
* Removes and returns the back item in the deque, or null if the deque is
* empty.
*
* @return The value of the removed back item, or null if the deque is empty.
*/
public String pollLast() {
if (isEmpty()) {
return null;
} else {
String value = getBack().getValue();
setBack(getBack().getPrev());
if (getBack() == null) {
setFront(null);
} else {
getBack().setNext(null);
}
return value;
}
}
/**
* Returns the value of the first item in the deque, or throws an exception if
* the deque is empty.
*
* @return The value of the first item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getFirst() { // TODO: change
// TODO: add check
return getFront().getValue();
}
/**
* Returns the value of the last item in the deque, or throws an exception if
* the deque is empty.
*
* @return The value of the last item in the deque.
* @throws NoSuchElementException if the deque is empty.
*/
public String getLast() { // TODO: change
// TODO: add check
return getBack().getValue();
}
/**
* Returns the number of items in the deque.
*
* @return The number of items in the deque.
*/
public int size() {
int count = 0;
Item current = getFront();
while (current != null) {
count++;
current = current.getNext();
}
return count;
}
/**
* Checks if the deque is empty.
*
* @return true if the deque is empty, false otherwise.
*/
public boolean isEmpty() {
return getFront() == null && getBack() == null;
}
/**
* Returns a string representation of the deque.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Item current = getFront();
sb.append("[");
while (current != null) {
sb.append(current.getValue());
current = current.getNext();
if (current != null) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
+154
View File
@@ -0,0 +1,154 @@
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Set;
public class InMemoryByteChannel implements SeekableByteChannel {
private final Path path;
private byte[] data;
private int position = 0;
private boolean isOpen = true;
private final boolean writable;
private final boolean forcedIOException;
public InMemoryByteChannel(Path path, Set<? extends OpenOption> options) {
this.path = path;
this.writable = options.contains(StandardOpenOption.WRITE) ||
options.contains(StandardOpenOption.CREATE) ||
options.contains(StandardOpenOption.CREATE_NEW);
this.forcedIOException = path.toString().contains("forcedIOException");
// Load existing data or create new
byte[] existingData = InMemoryFileSystem.getStorage().get(path.toString());
if (existingData != null) {
this.data = existingData.clone();
} else {
this.data = new byte[0];
}
if (options.contains(StandardOpenOption.TRUNCATE_EXISTING)) {
this.data = new byte[0];
}
if (options.contains(StandardOpenOption.APPEND)) {
this.position = data.length;
}
}
@Override
public int read(ByteBuffer dst) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (forcedIOException) {
throw new IOException("Forced IOException for testing purposes");
}
if (position >= data.length) {
return -1; // EOF
}
int remaining = Math.min(dst.remaining(), data.length - position);
dst.put(data, position, remaining);
position += remaining;
return remaining;
}
@Override
public int write(ByteBuffer src) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (!writable) {
throw new IOException("Channel is not writable");
}
int bytesToWrite = src.remaining();
int newSize = Math.max(data.length, position + bytesToWrite);
if (newSize > data.length) {
byte[] newData = new byte[newSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
src.get(data, position, bytesToWrite);
position += bytesToWrite;
return bytesToWrite;
}
@Override
public long position() throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
return position;
}
@Override
public SeekableByteChannel position(long newPosition) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (newPosition < 0) {
throw new IllegalArgumentException("Position cannot be negative");
}
this.position = (int) newPosition;
return this;
}
@Override
public long size() throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
return data.length;
}
@Override
public SeekableByteChannel truncate(long size) throws IOException {
if (!isOpen) {
throw new IOException("Channel is closed");
}
if (!writable) {
throw new IOException("Channel is not writable");
}
if (size < data.length) {
byte[] newData = new byte[(int) size];
System.arraycopy(data, 0, newData, 0, (int) size);
data = newData;
if (position > size) {
position = (int) size;
}
}
return this;
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public void close() throws IOException {
if (isOpen && writable) {
// Save data back to storage
InMemoryFileSystem.getStorage().put(path.toString(), data);
}
isOpen = false;
}
}
+88
View File
@@ -0,0 +1,88 @@
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class InMemoryFileSystem extends FileSystem {
private final String SEPARATOR = "/";
private static final Map<String, byte[]> storage = new ConcurrentHashMap<>();
private final InMemoryFileSystemProvider provider;
private boolean isOpen = true;
public InMemoryFileSystem(InMemoryFileSystemProvider provider) {
this.provider = provider;
}
public static Map<String, byte[]> getStorage() {
return storage;
}
@Override
public FileSystemProvider provider() {
return provider;
}
@Override
public void close() throws IOException {
isOpen = false;
}
@Override
public boolean isOpen() {
return isOpen;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public String getSeparator() {
return SEPARATOR;
}
@Override
public Iterable<Path> getRootDirectories() {
return Collections.singletonList(getPath(SEPARATOR));
}
@Override
public Iterable<FileStore> getFileStores() {
return Collections.emptyList();
}
@Override
public Set<String> supportedFileAttributeViews() {
return Collections.emptySet();
}
@Override
public Path getPath(String first, String... more) {
StringBuilder sb = new StringBuilder(first);
for (String part : more) {
if (!first.endsWith(SEPARATOR) && !part.startsWith(SEPARATOR)) {
sb.append(SEPARATOR);
}
sb.append(part);
}
return new InMemoryPath(this, sb.toString());
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
throw new UnsupportedOperationException();
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService() {
throw new UnsupportedOperationException();
}
@Override
public WatchService newWatchService() throws IOException {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,126 @@
import java.io.IOException;
import java.net.URI;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class InMemoryFileSystemProvider extends FileSystemProvider {
private static final String SCHEME = "memory";
private final Map<String, InMemoryFileSystem> fileSystems = new ConcurrentHashMap<>();
@Override
public String getScheme() {
return SCHEME;
}
@Override
public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
String key = uri.getHost();
if (key == null)
key = "default";
InMemoryFileSystem fs = new InMemoryFileSystem(this);
fileSystems.put(key, fs);
return fs;
}
@Override
public FileSystem getFileSystem(URI uri) {
String key = uri.getHost();
if (key == null)
key = "default";
InMemoryFileSystem fs = fileSystems.get(key);
if (fs == null) {
throw new FileSystemNotFoundException();
}
return fs;
}
@Override
public Path getPath(URI uri) {
return getFileSystem(uri).getPath(uri.getPath());
}
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
throws IOException {
return new InMemoryByteChannel(path, options);
}
@Override
public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
throws IOException {
throw new UnsupportedOperationException("Directory operations not supported");
}
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
// For simplicity, we'll just track that this directory exists
InMemoryFileSystem.getStorage().put(dir.toString() + "/", new byte[0]);
}
@Override
public void delete(Path path) throws IOException {
if (InMemoryFileSystem.getStorage().remove(path.toString()) == null) {
throw new NoSuchFileException(path.toString());
}
}
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
throw new UnsupportedOperationException("Copy operation not supported");
}
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
throw new UnsupportedOperationException("Move operation not supported");
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
throw new UnsupportedOperationException("isSameFile not supported");
}
@Override
public boolean isHidden(Path path) throws IOException {
throw new UnsupportedOperationException("Hidden file operations not supported");
}
@Override
public FileStore getFileStore(Path path) throws IOException {
throw new UnsupportedOperationException("FileStore operations not supported");
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
throw new UnsupportedOperationException("Check access not supported");
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
throw new UnsupportedOperationException("File attribute views not supported");
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
throw new UnsupportedOperationException("File attributes not supported");
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
throw new UnsupportedOperationException("Reading attributes not supported");
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new UnsupportedOperationException("Setting attributes not supported");
}
}
+175
View File
@@ -0,0 +1,175 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class InMemoryPath implements Path {
private final InMemoryFileSystem fileSystem;
private final String path;
private static final String SEPARATOR = "/";
public InMemoryPath(InMemoryFileSystem fileSystem, String path) {
this.fileSystem = fileSystem;
this.path = normalizePath(path);
}
private String normalizePath(String path) {
if (path == null || path.isEmpty()) {
return SEPARATOR;
}
if (!path.startsWith(SEPARATOR)) {
path = SEPARATOR + path;
}
return path;
}
@Override
public int compareTo(Path other) {
return this.path.compareTo(other.toString());
}
@Override
public boolean endsWith(Path other) {
return this.path.endsWith(other.toString());
}
@Override
public Path getFileName() {
int lastSeparator = path.lastIndexOf(SEPARATOR);
if (lastSeparator == -1 || lastSeparator == path.length() - 1) {
return this;
}
return new InMemoryPath(fileSystem, path.substring(lastSeparator + 1));
}
@Override
public FileSystem getFileSystem() {
return fileSystem;
}
@Override
public Path getName(int index) {
String[] parts = path.split(SEPARATOR);
if (index < 0 || index >= parts.length) {
throw new IllegalArgumentException("Index out of bounds");
}
return new InMemoryPath(fileSystem, parts[index]);
}
@Override
public int getNameCount() {
if (path.equals(SEPARATOR))
return 0;
return path.split(SEPARATOR).length - 1; // -1 because split on "/" creates empty first element
}
@Override
public Path getParent() {
int lastSeparator = path.lastIndexOf(SEPARATOR);
if (lastSeparator <= 0) {
return null;
}
return new InMemoryPath(fileSystem, path.substring(0, lastSeparator));
}
@Override
public Path getRoot() {
return new InMemoryPath(fileSystem, SEPARATOR);
}
@Override
public boolean isAbsolute() {
return path.startsWith(SEPARATOR);
}
@Override
public Path normalize() {
return this; // Already normalized in constructor
}
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events, Modifier... modifiers) throws IOException {
throw new UnsupportedOperationException("Watch service not supported");
}
@Override
public Path relativize(Path other) {
// Simplified implementation
return new InMemoryPath(fileSystem, other.toString());
}
@Override
public Path resolve(Path other) {
if (other.isAbsolute()) {
return other;
}
String resolvedPath = path;
if (!path.endsWith("/")) {
resolvedPath += "/";
}
resolvedPath += other.toString();
return new InMemoryPath(fileSystem, resolvedPath);
}
@Override
public boolean startsWith(Path other) {
return this.path.startsWith(other.toString());
}
@Override
public Path subpath(int beginIndex, int endIndex) {
String[] parts = path.split("/");
if (beginIndex < 0 || endIndex > parts.length - 1 || beginIndex >= endIndex) {
throw new IllegalArgumentException("Invalid indices");
}
StringBuilder sb = new StringBuilder();
for (int i = beginIndex + 1; i <= endIndex; i++) { // +1 because parts[0] is empty
if (!sb.isEmpty())
sb.append("/");
sb.append(parts[i]);
}
return new InMemoryPath(fileSystem, sb.toString());
}
@Override
public Path toAbsolutePath() {
return this; // Already absolute
}
@Override
public Path toRealPath(LinkOption... options) throws IOException {
return this;
}
@Override
public URI toUri() {
return URI.create("memory://default" + path);
}
@Override
public String toString() {
return path;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof InMemoryPath))
return false;
InMemoryPath other = (InMemoryPath) obj;
return path.equals(other.path);
}
@Override
public int hashCode() {
return path.hashCode();
}
}
+63
View File
@@ -0,0 +1,63 @@
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class InMemoryPathFactory {
private static InMemoryFileSystem fileSystem;
private InMemoryPathFactory() {
// Utility class - private constructor
}
static {
try {
// Create the in-memory file system
URI uri = URI.create("memory://default/");
Map<String, Object> env = new HashMap<>();
fileSystem = (InMemoryFileSystem) FileSystems.newFileSystem(uri, env);
} catch (IOException e) {
throw new RuntimeException("Failed to create in-memory file system", e);
}
}
/**
* Creates a new in-memory path
*
* @param path the path string
* @return a InMemoryPath that exists only in memory
*/
public static Path createPath(String path) {
return new InMemoryPath(fileSystem, path);
}
/**
* Gets the in-memory file system instance
*
* @return the file system
*/
public static FileSystem getFileSystem() {
return fileSystem;
}
/**
* Clears all data from the in-memory file system
*/
public static void clear() {
InMemoryFileSystem.getStorage().clear();
}
/**
* Checks if a path exists in memory
*
* @param path the path to check
* @return true if the path exists
*/
public static boolean exists(Path path) {
return InMemoryFileSystem.getStorage().containsKey(path.toString());
}
}
+86
View File
@@ -0,0 +1,86 @@
/**
* Represents an item in a doubly linked deque.
*/
public class Item {
/**
* The value of the item.
*/
private String value;
/**
* The previous item in the deque.
*/
private Item prev;
/**
* The next item in the deque.
*/
private Item next;
/**
* Constructor for creating a new item.
*
* @param value The value of the item.
*/
public Item(String value) {
this.value = value;
this.prev = null;
this.next = null;
}
/**
* Returns the value of the item.
*
* @return The value of the item.
*/
public String getValue() {
return value;
}
/**
* Sets the value of the item.
*
* @param value The value of the item.
*/
public void setValue(String value) {
this.value = value;
}
/**
* Returns the previous item in the deque.
*
* @return The previous item in the deque.
*/
public Item getPrev() {
return prev;
}
/**
* Sets the previous item in the deque.
*
* @param prev The previous item in the deque.
*/
public void setPrev(Item prev) {
this.prev = prev;
}
/**
* Returns the next item in the deque.
*
* @return The next item in the deque.
*/
public Item getNext() {
return next;
}
/**
* Sets the next item in the deque.
*
* @param next The next item in the deque.
*/
public void setNext(Item next) {
this.next = next;
}
}
@@ -0,0 +1 @@
InMemoryFileSystemProvider
+71
View File
@@ -0,0 +1,71 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 2 - I/O-Serialisierung von Listen");
System.out.println("=========================================");
System.out.println();
// Create a StringListSerializer to test our implementation
StringListSerializer serializer = new StringListSerializer();
Path erlkingPath = InMemoryPathFactory.createPath("/test/erlking.txt");
List<String> erlkingData = Arrays.asList(
"Who rides so late through night and wind?",
"It is the father with his child.",
"He holds the boy tightly in his arms,",
"He holds him safely, he keeps him warm.",
"My son, why do you hide your face so anxiously?",
"Father, do you not see the Erlking?",
"The Erlking with crown and tail?",
"My son, it is a streak of fog.",
"Come, go with me! Many pretty games I play with you;",
"Many colorful flowers are at the shore;",
"My mother has many golden garments.",
"Father, father, do you not hear what the Erlking promises me?",
"Be calm, stay calm, my child;",
"The wind rustles through the dry leaves.",
"Do you not want to come with me?",
"Father, father, do you not see the Erlking's daughter?",
"The Erlking's daughter with her golden garments?",
"My son, my son, I see it clearly:",
"The old willows look so gray and twisted.",
"I love you, I want to play with you,",
"And if you are not willing, I will use force.",
"Father, father, now he has seized me!",
"The Erlking has hurt me!",
"The father shudders, he rides swiftly,",
"He holds in his arms the moaning child,",
"He reaches the farmhouse with great effort;",
"In his arms, the child was dead.",
"- Johann Wolfgang von Goethe, 1782");
System.out.println("Writing 'Erlking' data to memory path: " + erlkingPath);
serializer.write(erlkingPath, erlkingData);
System.out.println("Wrote 'Erlking' data to memory path.");
System.out.println("");
System.out.println("Reading 'Erlking' data from memory path:");
List<String> erlkingReadData = serializer.read(erlkingPath);
for (String line : erlkingReadData) {
System.out.println(" " + line);
}
System.out.println("");
if (erlkingData.equals(erlkingReadData)) {
System.out.println("Read content matches original content.");
} else {
System.out.println("Read content does NOT match original content.");
}
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 3 - Exceptions");
System.out.println("=========================================");
System.out.println();
}
}
@@ -0,0 +1,16 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class StringListSerializer {
public void write(Path path, List<String> list) {
// TODO: implement
}
public List<String> read(Path path) {
// TODO: implement
return new ArrayList<>();
}
}
+694
View File
@@ -0,0 +1,694 @@
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
@Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte")
public void testTreeTraverse() {
int points = 20;
double[] values = new double[] { 3, 1, 5, 0, 2, 4, 6 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
double[] expect = new double[] { 3, 1, 0, 2, 5, 4, 6 };
TreeVisitor visitor = new TreeVisitor();
tree.traverse(visitor);
double[] actual = visitor.toArray();
if (!Arrays.equals(actual, expect)) {
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
Arrays.sort(expectSort);
Arrays.sort(actualSort);
if (Arrays.equals(expectSort, actualSort)) {
points -= 10;
TracingFramework.printError(
"Traversal " + Arrays.toString(actual) + " is not pre-order but complete. Deducting 10 points.");
} else {
points -= 20;
TracingFramework.printError("Traversal " + Arrays.toString(actual) + " is incomplete (no points).");
}
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count - 30 Punkte")
public void testTreeCount() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 5 should be found once
int count = tree.count(5);
if (count == 1) {
points += 7;
} else {
TracingFramework.printError("Count(5) should return 1 , but was " + count);
}
// 7 should not be found
count = tree.count(7);
if (count == 0) {
points += 8;
} else {
TracingFramework.printError("Count(7) should return 0 , but was " + count);
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
if (count == 2) {
points += 15;
} else if (count == 3) {
points += 8;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
}
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - height - 10 Punkte")
public void testTreeHeight() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
int height = tree.height();
if (height == 3) {
points += 10;
} else {
TracingFramework.printError("Height should return 3 , but was " + height);
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
serializer.write(path, data);
int points = 10;
try {
List<String> content = Files.readAllLines(path);
if (!content.equals(data)) {
points -= 10;
TracingFramework.printError("Written content does not match original content. Deducting 10 points.");
}
} catch (Exception e) {
points -= 10;
TracingFramework.printError("Failed to read written content: " + e.getMessage() + ". Deducting 10 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - errorless- 5 Punkte")
public void testIOReadErrorless() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/read.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
try {
Files.write(path, data);
} catch (IOException e) {
points -= 5;
e.printStackTrace();
TracingFramework.printError(
"Failed to write test data: " + e.getMessage() + ". Erroneous test. Giving full points.");
addPoints(points);
return;
}
List<String> readData = serializer.read(path);
if (!data.equals(readData)) {
points -= 5;
TracingFramework.printError("Read content does not match original content. Deducting 5 points.");
}
addPoints(points);
}
@Test(name = "Aufgabe 2 - IO - read - forced IOException - 5 Punkte")
public void testIOReadForcedIOException() {
int points = 5;
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/forcedIOException.txt");
try {
List<String> readData = serializer.read(path);
if (readData == null) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should return an empty list, but returned null. Deducting 5 points.");
} else if (!readData.isEmpty()) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should return an empty list, but returned: "
+ readData
+ ". Deducting 5 points.");
}
} catch (Exception e) {
if (e instanceof IOException) {
points -= 5;
TracingFramework.printError(
"Reading from /test/forcedIOException.txt path should process IOException to empty list, but did not. Deducting 5 points.");
} else {
points -= 5;
TracingFramework
.printError("Reading from /test/forcedIOException.txt path throws an unexpected exception: "
+ e.getMessage());
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst exception - 5 Punkte")
public void testDequeAddFirst() {
int points = 5;
boolean valid = true;
Deque deque = new Deque();
try {
deque.addFirst("A");
deque.addFirst("BCDEF");
deque.addFirst("Hallo");
} catch (Exception e) {
valid = false;
points -= 5;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception: "
+ e.getMessage()
+ ". Assuming method always throws an exception on valid values. Deducting 5 points.");
}
if (valid) {
try {
deque.addFirst(null);
TracingFramework
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 2 points.");
points -= 2;
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
TracingFramework
.printError("Deque.addFirst(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
TracingFramework.printError(
"Deque.addFirst(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
try {
deque.addFirst("");
TracingFramework
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 2 points.");
points -= 2;
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
TracingFramework
.printError("Deque.addFirst(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
TracingFramework.printError(
"Deque.addFirst(\"\") should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("addFirst", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
TracingFramework.printError(
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast exception - 5 Punkte")
public void testDequeAddLast() {
int points = 5;
boolean valid = true;
Deque deque = new Deque();
try {
deque.addLast("A");
deque.addLast("BCDEF");
deque.addLast("Hallo");
} catch (Exception e) {
valid = false;
points -= 5;
TracingFramework
.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception: "
+ e.getMessage()
+ ". Assuming method always throws an exception on valid values. Deducting 5 points.");
}
if (valid) {
try {
deque.addLast(null);
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 2 points.");
points -= 2;
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
TracingFramework
.printError("Deque.addLast(null) should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
points -= 1;
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be null")) {
TracingFramework.printError(
"Deque.addLast(null) should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
try {
deque.addLast("");
TracingFramework
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 2 points.");
points -= 2;
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
TracingFramework
.printError("Deque.addLast(\"\") should throw an IllegalArgumentException, but threw: "
+ e.getClass().getName() + ". Deducting 1 point.");
}
if (e.getMessage() == null || !e.getMessage().equals("Value cannot be empty")) {
TracingFramework.printError(
"Deque.addLast(\"\") should throw an IllegalArgumentException with message 'Value cannot be null', but got: "
+ e.getMessage() + ". Deducting 1 point.");
points -= 1;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("addLast", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.addLast(String) should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
TracingFramework.printError(
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst exception - 5 Punkte")
public void testDequeGetFirst() {
int points = 5;
boolean valid = true;
Deque deque = buildDeque("A", "BCDEF", "Hallo");
try {
deque.getFirst();
} catch (Exception e) {
valid = false;
points -= 5;
TracingFramework.printError(
"Deque.getFirst() threw an exception: " + e.getMessage()
+ ". Assuming method always throws an exception on none empty deque. Deducting 5 points.");
}
if (valid) {
setFront(deque, null);
setBack(deque, null);
try {
deque.getFirst();
TracingFramework.printError(
"Deque.getFirst() should throw an exception on empty deque, but did not. Deducting 4 points.");
points -= 4;
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 2 point.");
points -= 2;
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 2 points.");
points -= 2;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("getFirst");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (Exception e) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast exception - 5 Punkte")
public void testDequeGetLast() {
int points = 5;
boolean valid = true;
Deque deque = buildDeque("A", "BCDEF", "Hallo");
try {
deque.getLast();
} catch (Exception e) {
valid = false;
points -= 5;
TracingFramework.printError(
"Deque.getLast() threw an exception: " + e.getMessage()
+ ". Assuming method always throws an exception on none empty deque. Deducting 5 points.");
}
if (valid) {
setFront(deque, null);
setBack(deque, null);
try {
deque.getLast();
TracingFramework.printError(
"Deque.getLast() should throw an exception on empty deque, but did not. Deducting 4 points.");
points -= 4;
} catch (Exception e) {
if (!(e instanceof NoSuchElementException)) {
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException on empty deque, but threw: "
+ e.getClass().getName() + ". Deducting 2 point.");
points -= 2;
}
if (e.getMessage() == null || !e.getMessage().equals("Deque is empty")) {
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException with message 'Deque is empty', but got: "
+ e.getMessage() + ". Deducting 2 points.");
points -= 2;
}
}
}
try {
Method method = Deque.class.getDeclaredMethod("getLast");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 1 point.");
points -= 1;
} else if (exceptionTypes.length != 1) {
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 1 point.");
points -= 1;
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 1 point.");
points -= 1;
}
}
} catch (Exception e) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
}
addPoints(points);
}
public Deque buildDeque(String... values) {
Deque deque = new Deque();
for (String value : values) {
try {
// Create new Item
Item item = new Item(value);
// If deque is empty, set both front and back to this item
if (deque.peekFirst() == null) {
setFront(deque, item);
setBack(deque, item);
} else {
// Add to the end (back) of the deque
Item currentBack = getBack(deque);
// Set the links
setNext(currentBack, item);
setPrev(item, currentBack);
// Update back pointer
setBack(deque, item);
}
} catch (Exception e) {
throw new RuntimeException("Failed to build deque: " + e.getMessage(), e);
}
}
return deque;
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
*
* @param values The values.
* @return The tree node representing the root.
*/
private TreeNode buildTree(double[] values) {
TreeNode root = new TreeNode(values[0]);
java.util.List<TreeNode> nodes = new ArrayList<>();
nodes.add(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = nodes.get(0);
TreeNode child = new TreeNode(values[i]);
nodes.add(child);
if (i % 2 == 1) {
parent.setLeft(child);
} else {
parent.setRight(child);
nodes.remove(0);
}
}
return root;
}
/**
* Sets the root in the tree.
*
* @param tree The tree.
* @param root The root to set in the tree.
*/
private void setRoot(Tree tree, TreeNode root) {
try {
Field field = Tree.class.getDeclaredField("root");
field.setAccessible(true);
field.set(tree, root);
} catch (Exception e) {
throw new RuntimeException("Failed to set root.");
}
}
/**
* Sets the front item in the deque using reflection.
*
* @param deque The deque.
* @param item The item to set as front.
*/
private void setFront(Deque deque, Item item) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, item);
} catch (Exception e) {
throw new RuntimeException("Failed to set front.");
}
}
/**
* Sets the back item in the deque using reflection.
*
* @param deque The deque.
* @param item The item to set as back.
*/
private void setBack(Deque deque, Item item) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, item);
} catch (Exception e) {
throw new RuntimeException("Failed to set back.");
}
}
/**
* Gets the back item from the deque using reflection.
*
* @param deque The deque.
* @return The back item.
*/
private Item getBack(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (Exception e) {
throw new RuntimeException("Failed to get back.");
}
}
/**
* Sets the next item in an Item using reflection.
*
* @param item The item.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
try {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
field.set(item, next);
} catch (Exception e) {
throw new RuntimeException("Failed to set next.");
}
}
/**
* Sets the previous item in an Item using reflection.
*
* @param item The item.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
try {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);
field.set(item, prev);
} catch (Exception e) {
throw new RuntimeException("Failed to set prev.");
}
}
/**
* The points of each test case.
*/
private java.util.List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all test have been executed to get
* the resulting points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes that the method is called
* <b>exactly</b> once per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
/**
* A utility method to execute any test driver class extending abstract test
* locally without going through Jack.
*
* @param test The test driver to execute.
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
try {
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name()
+ " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+144
View File
@@ -0,0 +1,144 @@
/**
* An ordered binary tree.
*
* @author Marcus
*/
public class Tree {
/**
* The root node of the tree.
*/
private TreeNode root;
/**
* Creates a new and empty tree.
*/
public Tree() {
super();
}
/**
* Traverses the tree and calls the visitor's
* visit(TreeNode) method in pre-order.
*
* @param visitor The visitor whose visit method
* shall be called in pre-order.
*/
public void traverse(TreeVisitor visitor) {
traverse(visitor, root);
}
/**
* Traverses the subtree starting at current
* and calls the visitor's visit(TreeNode)
* method in pre-order.
*
* @param visitor The visitor.
* @param current The subtree to visit, may be null.
*/
private void traverse(TreeVisitor visitor, TreeNode current) {
if (current == null)
return;
// TODO: implement
}
/**
* Inserts a new value into the true.
*
* @param value The value to insert.
*/
public void insert(double value) {
if (root == null) {
root = new TreeNode(value);
} else {
insert(value, root);
}
}
/**
* Recursively finds the right node to insert the
* value and inserts it.
*
* @param value The value to insert.
* @param current The current value.
*/
private void insert(double value, TreeNode current) {
if (value <= current.getValue()) {
// smaller or equal values go left
if (current.getLeft() == null) {
current.setLeft(new TreeNode(value));
} else {
insert(value, current.getLeft());
}
} else {
// larger values go right
if (current.getRight() == null) {
current.setRight(new TreeNode(value));
} else {
insert(value, current.getRight());
}
}
}
/**
* Efficiently counts the number of nodes in the
* tree that have a particular value by considering
* the order that is defined by the tree's insert
* method.
*
* @param value The value to search from.
* @return The number of nodes with the value.
*/
public int count(double value) {
return count(value, root);
}
/**
* Efficiently counts the number of nodes in the
* subtree starting at current that have a particular
* value by considering the order that is defined
* by the tree's insert method.
*
* @param value The value to search from.
* @param current The subtree to search in, may be null.
* @return The number of nodes with the value.
*/
private int count(double value, TreeNode current) {
if (current == null)
return 0;
// TODO: implement
return -42;
}
/**
* Calculates the height of the tree total tree.
*
* @return The height of the tree, which is the
* number of edges on the longest path from the root
* to a leaf node. If the tree is empty, returns 0.
* If the tree has only one node, returns 1.
*/
public int height() {
return height(root);
}
/**
* Calculates the height of the subtree
* starting at current.
*
* @param current The subtree to calculate the height of, may be null.
* If null, the height is 0.
* @return The height of the subtree, which is the
* number of edges on the longest path from the current node
* to a leaf node. If the subtree is empty, returns 0.
* If the subtree has only one node, returns 1.
* If the subtree has only two nodes, returns 2.
* If the subtree has three nodes, returns 3.
* And so on.
*/
public int height(TreeNode current) {
// TODO: implement
return -42;
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* A node of a binary tree.
*
* @author Marcus
*/
public class TreeNode {
/**
* The value of the node.
*/
private double value;
/**
* The left child, or null.
*/
private TreeNode left;
/**
* The right child, or null.
*/
private TreeNode right;
/**
* Creates a new tree node with
* the specified value and no
* children.
*
* @param value The value to set.
*/
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
* @return The value of the node.
*/
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
* @return The left child or null.
*/
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
* @return The right child or null.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
* @param left The new left child.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right The new right child.
*/
public void setRight(TreeNode right) {
this.right = right;
}
}
+72
View File
@@ -0,0 +1,72 @@
import java.util.ArrayList;
import java.util.List;
/**
* A visitor to test the implementation.
*
* @author Marcus
*/
public class TreeVisitor {
/**
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
* @return The visited nodes.
*/
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
*
* @param node The node to visit.
*/
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
*
* @return The array with the node values.
*/
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result[i] = Integer.MAX_VALUE;
else result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result += "[NULL]";
else result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}
@@ -0,0 +1,19 @@
package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TracingFramework {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Test {
String name();
}
public static void printError(String string) {
System.err.println("ERROR: " + string);
}
}