Vollständige Java 8 Kompatibilität hinzugefügt.

This commit is contained in:
2025-09-11 01:23:17 +02:00
parent c9355b3a08
commit 1d45824d55
34 changed files with 1795 additions and 1286 deletions
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -29,8 +29,7 @@ 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:
getInfo(), die einen String zurückgeben soll, der folgendermaßen aufgebaut ist:
<Vorname des Autors> <Nachname des Autors>: <Titel> (<Erscheinungsjahr>)
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -28,8 +28,8 @@ 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.
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.
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -28,8 +28,8 @@ Die Methode calculateMeanBelow der Klasse Testat1B soll für alle Werte des
übergebenen Arrays arr, welche KLEINER 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.
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.
@@ -37,8 +37,8 @@ Hinweis: Beachten Sie, dass eine Division durch 0 zu einem Fehler führt.
Aufgabe 2 - 2d-Arrays - 25 Punkte
Die Methode calculateColumnMean in der Klasse Testat1B erhält ein
2-dimensionales Array und soll den Durchschnitt für jede Spalte berechnen und
in einem neuen Array zurückgeben.
2-dimensionales Array und soll den Durchschnitt für jede Spalte berechnen und in
einem neuen Array zurückgeben.
Die erste Dimension des 2-dimensionalen Arrays addressiert die Spalte, die
zweite Dimension die Reihe. D.h. int x = arr[0][1] weist x den Wert der Spalte 0
@@ -99,8 +99,7 @@ Leerzeichen, kleines m, kleines i, kleines n,, Klammer zu)
Ergänzen Sie die Klassen Series und Movie wie folgt:
----- e) -----
Ändern Sie die Vererbungsbeziehungen so, dass beide Klassen von MediaItem
erben.
Ändern Sie die Vererbungsbeziehungen so, dass beide Klassen von MediaItem erben.
----- f) -----
Fügen Sie den Klassen den Konstruktor Ihrer neuen Superklasse hinzu und geben
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -30,21 +30,20 @@ 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).
(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.
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.
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).
@@ -100,4 +99,4 @@ Falls die Deque leer ist, soll null zurückgegeben werden.
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.
Verändern Sie nichts außerhalb der genannten Methoden in der Klasse Deque.
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -38,13 +38,12 @@ es noch Platz gibt (also items.length < maxItems).
Erweitern Sie die Klasse wie folgt:
----- a) -----
Implementieren Sie die Schnittstelle Lasting und geben Sie über die
getDuration-Methode die Summe der Dauern aller Medienelemente der Mediathek
zurück.
Implementieren Sie die Schnittstelle Lasting und geben Sie über die getDuration-
Methode die Summe der Dauern aller Medienelemente der Mediathek zurück.
----- b) -----
Ergänzen Sie die Prüfungen in der addItem-Methode so dass diese zusätzlich
noch sicherstellt, dass ein Medienelement nur dann hinzugefügt wird.
Ergänzen Sie die Prüfungen in der addItem-Methode so dass diese zusätzlich noch
sicherstellt, dass ein Medienelement nur dann hinzugefügt wird.
– wenn es sich noch nicht in der Mediathek befindet (Tipp: containsItem)
– wenn dadurch die maximale Dauer (gespeichert in der Instanzvariable
"maxDuration") nicht überschritten wird (Tipp: getDuration).
@@ -100,4 +99,4 @@ Falls die Deque leer ist, soll null zurückgegeben werden.
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.
Verändern Sie nichts außerhalb der genannten Methoden in der Klasse Deque.
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -51,8 +51,8 @@ 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.
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.
@@ -65,8 +65,7 @@ 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.
- Allgemein ist die Höhe eines Baums 1 plus die maximale Höhe seiner Teilbäume.
================================================================================
@@ -77,9 +76,9 @@ 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.
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.
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -38,9 +38,9 @@ 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 Nebenreihenfolge (post-order) aufgerufen werden
(d.h. für jeden Teilbaum erst den Teilbaum des linken Kinds und dann den
Teilbaum des rechten Kinds und schließlich die Wurzel).
übergebenen Visitor in der Nebenreihenfolge (post-order) aufgerufen werden (d.h.
für jeden Teilbaum erst den Teilbaum des linken Kinds und dann den Teilbaum des
rechten Kinds und schließlich die Wurzel).
Tipp: Falls Sie die Nebenreihenfolge (post-order) nicht verstehen,
implementieren Sie irgendeine vollständige Traversierung, um zumindest
@@ -52,8 +52,8 @@ 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.
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.
@@ -66,8 +66,7 @@ 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.
- Allgemein ist die Höhe eines Baums 1 plus die maximale Höhe seiner Teilbäume.
================================================================================
@@ -78,9 +77,9 @@ 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.
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.
@@ -7,16 +7,16 @@ WICHTIGE HINWEISE
- Sofern nicht anders beschrieben, ändern Sie die Methodensignaturen bitte
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 Versuch wird bewertet.
- Vergessen Sie nicht ihre Lösungen hochzuladen. Sie dürfen so oft hochladen wie
Sie wollen, der beste Versuch wird bewertet.
- Folgen Sie den unten stehenden Aufgabenstellungen und den entsprechenden
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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
für die finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle
bestehen, erhalten Sie nicht automatisch die volle Punktzahl.
Kommentaren in den Klassen aufmerksam. Bei Unklarheiten dürfen 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 für die
finale Bewertung ausgeführt werden. D.h. nur weil Sie diese Testfälle bestehen,
erhalten Sie nicht automatisch die volle Punktzahl.
Wir wünschen viel Erfolg!
@@ -37,8 +37,7 @@ 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.
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.
@@ -24,4 +24,4 @@ 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.
Verändern Sie nichts außerhalb der genannten Methoden in der Klasse Deque.
@@ -24,4 +24,4 @@ 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.
Verändern Sie nichts außerhalb der genannten Methoden in der Klasse Deque.
+5
View File
@@ -11,6 +11,11 @@ public class Cheese extends FridgeItem {
super(weight, name, color);
}
/**
* Returns a string representation of the cheese.
*
* @return A string representation of the cheese.
*/
@Override
public String toString() {
return "Cheese: " + super.toString();
+2 -2
View File
@@ -136,8 +136,8 @@ public class Fridge { // TODO: change
sb.append(", ");
}
}
if (this instanceof Weightful weightful) {
sb.append("Weight: " + weightful.getWeight() + " kg");
if (this instanceof Weightful) {
sb.append("Weight: " + ((Weightful) this).getWeight() + " kg");
}
return sb.toString();
}
+10 -2
View File
@@ -46,12 +46,20 @@ public class FridgeItem implements Weightful {
return color;
}
@Override
/**
* Returns the weight of the item.
*
* @return The weight of the item.
*/
public double getWeight() {
return weight;
}
@Override
/**
* Returns a string representation of the item.
*
* @return A string representation of the item.
*/
public String toString() {
return name + " (" + color + " " + weight + " g)";
}
+26 -17
View File
@@ -6,8 +6,13 @@ public class Main {
* 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("");
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 1 - Fridge");
System.out.println("=========================================");
System.out.println();
// create items
FridgeItem gouda = new Cheese(500.5, "Gouda", "yellow");
FridgeItem cheddar = new Cheese(1123.75, "Cheddar", "orange");
@@ -27,18 +32,7 @@ public class Main {
} 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.");
}
System.out.println();
boolean addCherryYoghurt = fridge.addItem(cherryYoghurt);
if (addCherryYoghurt) {
@@ -53,6 +47,18 @@ public class Main {
}
System.out.println();
boolean addVanillaYoghurt = fridge.addItem(vanillaYoghurt);
if (addVanillaYoghurt) {
System.out.println("Failure: The vanilla yoghurt should be too heavy.");
} else {
System.out.println("Success: The vanilla yoghurt 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.");
}
// Aufgabe 1 - indexOf
System.out.println("Testing: Fridge.indexOf()");
System.out.println("Fridge.indexOf(cheddar.getName(), 0) Expected: 0, Your code: "
@@ -67,9 +73,12 @@ public class Main {
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("");
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 2 - Deque");
System.out.println("=========================================");
System.out.println();
// create a deque
Deque deque = new Deque();
+452 -266
View File
@@ -1,70 +1,40 @@
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();
}
private static final String TESTAT_NAME = "Testat 2A";
}
System.out.println();
System.out.println(String.format("Total points: %d", test.getResult()));
}
// Aufgabe 1 - Fridge tests - 50 Punkte
@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()) {
Method method = findMethod(Fridge.class, "getWeight", double.class);
if (method == null) {
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"));
setItems(fridge, new FridgeItem[] { new Cheese(100, "A", "B"), new Cheese(100, "C", "D"),
new Cheese(100, "E", "F") });
try {
double weight = (double) getWeight.invoke(fridge);
double weight = (double) method.invoke(fridge);
if (weight != 300.0) {
points -= 3;
TracingFramework.printError(
@@ -75,6 +45,7 @@ public class Tests {
TracingFramework.printError("Error invoking getWeight method: " + e.getMessage());
}
}
addPoints(points);
}
@@ -95,11 +66,11 @@ public class Tests {
boolean duplicates = fridge.addItem(a);
if (getItems(fridge).length == 3) {
if (duplicates) {
points -= 2;
points -= 3;
TracingFramework.printError("Note: The fridge should return false for duplicates.");
}
} else {
points -= 4;
points -= 6;
TracingFramework.printError("The fridge does not check for duplicates.");
}
@@ -109,19 +80,19 @@ public class Tests {
boolean weight = fridge.addItem(new Cheese(8, "D", "E"));
if (getItems(fridge).length == 3) {
if (weight) {
points -= 2;
points -= 3;
TracingFramework.printError("Note: The fridge should return false for exceeded weight.");
}
} else {
points -= 4;
points -= 6;
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"));
fridge.addItem(new Cheese(7, "G", "H"));
if (getItems(fridge).length == 3) {
points -= 2;
points -= 3;
TracingFramework
.printError("Note: The fridge doesn't add an item when it hits exactly the maximum weight.");
}
@@ -131,28 +102,24 @@ public class Tests {
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"));
setItems(fridge, new FridgeItem[] { new Cheese(1, "A", "B"), new Cheese(1, "B", "C"),
new Cheese(1, "C", "D"), new Cheese(1, "A", "B"), new Cheese(1, "B", "C"), new Cheese(1, "C", "D"),
new Cheese(1, "A", "B"), new Cheese(1, "B", "C"), 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"))
.filter(element -> element.getClassName().equals(Fridge.class.getName())
&& 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
@@ -172,6 +139,7 @@ public class Tests {
@Test(name = "Aufgabe 1 - Fridge - indexOf - existing item - 5 Punkte")
public void testFridgeIndexOfExisting() {
int points = 5;
TraceableFridge fridge = createTraceableFridge();
// test for existing item
@@ -193,6 +161,7 @@ public class Tests {
@Test(name = "Aufgabe 1 - Fridge - indexOf - shifted start - 10 Punkte")
public void testFridgeIndexOfShiftedStart() {
int points = 10;
TraceableFridge fridge = createTraceableFridge();
// test for shifted start
@@ -211,9 +180,12 @@ public class Tests {
addPoints(points);
}
// Aufgabe 2 - Deque tests - 50 Punkte
@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) {
@@ -236,17 +208,25 @@ public class Tests {
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - addLast - null or empty values - 5 Punkte")
public void testDequeAddLastNullOrEmpty() {
int points = 5;
@Test(name = "Aufgabe 2 - Deque - addLast - null value - 3 Punkte")
public void testDequeAddLastNull() {
int points = 3;
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();
addPoints(points);
}
@Test(name = "Aufgabe 2 - Deque - addLast - empty value - 2 Punkte")
public void testDequeAddLastEmpty() {
int points = 2;
Deque deque = new Deque();
deque.addLast("");
if (getFront(deque) != null || getBack(deque) != null) {
points -= 2;
@@ -283,11 +263,10 @@ public class Tests {
public void testDequePeekFirstEmpty() {
int points = 5;
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.peekFirst();
if (value == null) {
if (hasInvalidFirstPeeking()) {
points -= 5;
TracingFramework.printError(
"The peekFirst method returns null for an non empty deque, assuming it always returns null. Deducting 5 points.");
"The peekFirst method should not return null for a non-empty deque, assuming it always returns null. Deducting 5 points.");
} else {
// empty the deque
pollFirst(deque);
@@ -295,7 +274,7 @@ public class Tests {
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
value = deque.peekFirst();
String value = deque.peekFirst();
if (value != null) {
points -= 5;
TracingFramework
@@ -306,6 +285,14 @@ public class Tests {
addPoints(points);
}
private boolean hasInvalidFirstPeeking() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.peekFirst();
// if value is null, we assume that the return value of peekFirst is always null
// without checking would always return null, and therefore granting full points
return value == null;
}
@Test(name = "Aufgabe 2 - Deque - pollLast - filled deque - 10 Punkte")
public void testDequePollLastFilled() {
int points = 10;
@@ -332,9 +319,9 @@ public class Tests {
@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) {
if (hasInvalidLastPolling()) {
points -= 5;
TracingFramework.printError(
"The pollLast method returns null for an non empty deque, assuming it always returns null. Deducting 5 points.");
@@ -345,7 +332,7 @@ public class Tests {
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
value = deque.pollLast();
String value = deque.pollLast();
if (value != null) {
points -= 5;
TracingFramework
@@ -356,14 +343,30 @@ public class Tests {
addPoints(points);
}
public boolean hasInvalidLastPolling() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
String value = deque.pollLast();
// if value is null, we assume that the return value of pollLast is always null
// without checking would always return null, and therefore granting full points
return value == null;
}
@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.");
if (hasIllegalDequeFields()) {
points = 0;
TracingFramework.printError(
"Fields of Deque class were modified illegally. Cannot determine if field for size was added. Deducting all points for size tests.");
} else {
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);
@@ -372,133 +375,75 @@ public class Tests {
@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.");
if (hasIllegalDequeFields()) {
points = 0;
TracingFramework.printError(
"Fields of Deque class were modified illegally. Cannot determine if field for size was added. Deducting all points for size tests.");
} else {
// empty the deque
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
pollFirst(deque);
size = deque.size();
if (size != 0) {
Deque deque = buildDeque("A", "B", "C", "D", "E");
int 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.");
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) {
/**
* Finds a method with the given name, return type, and parameter types in the
* specified class or its superclasses.
*
* @param clazz The class to search in.
* @param methodName The name of the method to find.
* @param returnType The return type of the method.
* @param parameterTypes The parameter types of the method.
* @return The method if found, null otherwise.
*/
public static Method findMethod(Class<?> clazz, String methodName, Class<?> returnType,
Class<?>... parameterTypes) {
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);
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
if (method.getReturnType().equals(returnType)) {
return method;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
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);
}
/**
* Checks if a class implements a given interface.
*
* @param clazz The class to check.
* @param interfaceClass The interface to check for.
* @return True if the class implements the interface, false otherwise.
*/
public static boolean implementsInterface(Class<?> clazz, Class<?> interfaceClass) {
Class<?>[] interfaces = clazz.getInterfaces();
return Arrays.stream(interfaces).anyMatch(interfaceClass::equals);
}
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);
}
}
/**
* START: Fridge helper methods
*/
/**
* Sets the fridge items.
@@ -506,7 +451,7 @@ public class Tests {
* @param fridge The fridge.
* @param items The items.
*/
private void setItems(Fridge fridge, FridgeItem[] items) {
private static void setItems(Fridge fridge, FridgeItem[] items) {
try {
Field f = Fridge.class.getDeclaredField("items");
f.setAccessible(true);
@@ -516,87 +461,6 @@ public class Tests {
}
}
/**
* 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.
*
@@ -613,4 +477,326 @@ public class Tests {
return new FridgeItem[0];
}
}
/**
* END: Fridge helper methods
*/
/**
* START: Deque helper methods
*/
/**
* Checks if the Deque class has illegal fields.
* The Deque class should only have two fields: 'front' and 'back', both of type
* Item.
*
* Check to be used in tests to ensure no extra fields are added.
*
* Size is supposed to be determined by iterating through the items, not by a
* field. Because given methods don't make use of such a field.
*
* @return True if illegal fields are found, false otherwise.
*/
public boolean hasIllegalDequeFields() {
Field[] fields = Deque.class.getDeclaredFields();
if (fields.length != 2) {
TracingFramework.printError("Deque class should have exactly 2 fields. But has: " + fields.length);
return true;
}
for (Field field : fields) {
String fieldName = field.getName();
if (fieldName.equals("front") || fieldName.equals("back")) {
if (!field.getType().equals(Item.class)) {
TracingFramework.printError("Field " + fieldName + " should be of type Item.");
return true;
}
} else {
TracingFramework.printError("Deque class has an illegal field: " + fieldName);
return true;
}
}
return false;
}
/**
* Builds a deque from the given values.
*
* @param values The values to add.
* @return The built deque.
*/
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;
}
/**
* Removes and returns the first element of the deque.
*
* @param deque The deque to poll from.
* @return The value of the first element, or null if the deque is empty.
*/
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;
}
/**
* Peeks at the first element of the deque without removing it.
*
* @param deque The deque to peek from.
* @return The value of the first element, or null if the deque is empty.
*/
private String peekFirst(Deque deque) {
Item first = getFront(deque);
return first != null ? first.getValue() : null;
}
/**
* Peeks at the last element of the deque without removing it.
*
* @param deque The deque to peek from.
* @return The value of the last element, or null if the deque is empty.
*/
private String peekLast(Deque deque) {
Item last = getBack(deque);
return last != null ? last.getValue() : null;
}
/**
* Peeks at the last element of the deque by traversing from the front.
*
* @param deque The deque to peek from.
* @return The value of the last element, or null if the deque is empty.
*/
private String peekLastFromFront(Deque deque) {
Item last = getLastFromFront(deque);
return last != null ? last.getValue() : null;
}
/**
* Gets the last item by traversing from the front.
*
* @param deque The deque to get the last item from.
* @return The last item, or null if the deque is empty.
*/
private Item getLastFromFront(Deque deque) {
Item current = getFront(deque);
while (current != null && current.getNext() != null) {
current = current.getNext();
}
return current;
}
/**
* Gets the front item of the deque.
*
* @param deque The deque to get the front item from.
* @return The front item, or null if the deque is empty.
*/
private Item getFront(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getFront method", e);
}
}
/**
* Gets the back item of the deque.
*
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
private Item getBack(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
}
/**
* Sets the front item of the deque.
*
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, front);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting front item", e);
}
}
/**
* Sets the back item of the deque.
*
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, back);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting back item", e);
}
}
/**
* Sets the next item for the given item.
*
* @param item The item to set the next item for.
* @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 (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting next item", e);
}
}
/**
* Sets the previous item for the given item.
*
* @param item The item to set the previous item for.
* @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 (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting previous item", e);
}
}
/**
* END: Deque helper methods
*/
/**
* 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);
}
/**
* 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 {
Class<Tests> clazz = Tests.class;
Tests test = new Tests();
System.out.println(String.format("Running tests for: %s", TESTAT_NAME));
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()));
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+5 -1
View File
@@ -7,11 +7,15 @@ public class Yoghurt extends FridgeItem {
* @param name The name.
* @param color The color.
*/
public Yoghurt(double weight, String name, String color) {
super(weight, name, color);
}
/**
* Returns a string representation of the yoghurt.
*
* @return A string representation of the yoghurt.
*/
@Override
public String toString() {
return "Yoghurt: " + super.toString();
+12 -5
View File
@@ -6,8 +6,12 @@ public class Main {
* sondern nur einige, die Ihnen helfen sollen, Ihre Lösungen zu überprüfen.
*/
public static void main(String[] args) {
System.out.println("Aufgabe 1: MediaLibrary");
System.out.println("");
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 1 - MediaLibrary");
System.out.println("=========================================");
System.out.println();
// create items
MediaItem longMovie = new Movie(241, "The Lord of the Rings", 5);
MediaItem shortMovie = new Movie(109, "Deadpool", 42);
@@ -87,9 +91,12 @@ public class Main {
System.out.println("MediaLibrary.lastIndexOf(shortMovie.getTitle(), 3) Expected: 3, Your code: "
+ mediaLibrary.lastIndexOf(shortMovie.getTitle(), 3));
System.out.println("");
System.out.println("Aufgabe 2: Deque");
System.out.println("");
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 2 - Deque");
System.out.println("=========================================");
System.out.println();
// create a deque
Deque deque = new Deque();
+2 -1
View File
@@ -20,6 +20,7 @@ public class MediaItem implements Lasting {
*
* @param title The title of the item.
* @param duration The duration of the item.
* @param views The views of the item.
*/
public MediaItem(int duration, String title, int views) {
this.duration = duration;
@@ -63,4 +64,4 @@ public class MediaItem implements Lasting {
return title + " (" + views + " " + duration + " min)";
}
}
}
+4 -1
View File
@@ -57,7 +57,7 @@ public class MediaLibrary { // TODO: change
public boolean addItem(MediaItem item) { // TODO: add more checks
// check invalid states
if (item == null) { // Cannot add null item, sorry
return false;
return false;
}
if (items.length == maxItems) { // Cannot add more items to the media library
return false;
@@ -121,6 +121,9 @@ public class MediaLibrary { // TODO: change
return false;
}
/**
* Returns a string representation of the media library.
*/
@Override
public String toString() {
String result = "";
+387 -242
View File
@@ -1,47 +1,18 @@
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();
}
private static final String TESTAT_NAME = "Testat 2B";
}
System.out.println();
System.out.println(String.format("Total points: %d", test.getResult()));
}
// Aufgabe 1 - MediaLibrary tests - 50 Punkte
@Test(name = "Aufgabe 1 - MediaLibrary - getDuration - 10 Punkte")
public void testMediaLibraryLasting() {
@@ -51,20 +22,19 @@ public class Tests {
TracingFramework
.printError("MediaLibrary should implement interface Lasting, but does not. Deducting 5 points.");
}
Optional<Method> method = findMethod(MediaLibrary.class, "getDuration", int.class);
if (method.isEmpty()) {
Method method = findMethod(MediaLibrary.class, "getDuration", int.class);
if (method == null) {
points -= 5;
TracingFramework.printError(
"MediaLibrary should implement method getDuration with return type int, but does not. Deducting 5 points.");
} else {
Method getDuration = method.get();
MediaLibrary mediaLibrary = new MediaLibrary(10, 500);
mediaLibrary.addItem(new MediaItem(100, "A", 0));
mediaLibrary.addItem(new MediaItem(100, "B", 0));
mediaLibrary.addItem(new MediaItem(100, "C", 0));
try {
int duration = (int) getDuration.invoke(mediaLibrary);
int duration = (int) method.invoke(mediaLibrary);
if (duration != 300) {
points -= 3;
TracingFramework.printError(
@@ -133,22 +103,18 @@ public class Tests {
private static TraceableMediaLibrary createTraceableMediaLibrary() {
TraceableMediaLibrary mediaLibrary = new TraceableMediaLibrary(10, 10);
mediaLibrary.addItem(new Series(1, "A", 0));
mediaLibrary.addItem(new Series(1, "B", 0));
mediaLibrary.addItem(new Series(1, "C", 0));
mediaLibrary.addItem(new Series(1, "A", 0));
mediaLibrary.addItem(new Series(1, "B", 0));
mediaLibrary.addItem(new Series(1, "C", 0));
mediaLibrary.addItem(new Series(1, "A", 0));
mediaLibrary.addItem(new Series(1, "B", 0));
mediaLibrary.addItem(new Series(1, "C", 0));
setItems(mediaLibrary,
new MediaItem[] { new Series(1, "A", 0), new Series(1, "B", 0), new Series(1, "C", 0),
new Series(1, "A", 0),
new Series(1, "B", 0), new Series(1, "C", 0), new Series(1, "A", 0), new Series(1, "B", 0),
new Series(1, "C", 0) });
return mediaLibrary;
}
private static long countRecursionSteps(TraceableMediaLibrary mediaLibrary) {
List<StackTraceElement> stackTrace = mediaLibrary.getStackTrace();
return stackTrace.stream()
.filter(element -> element.getClassName().equals("MediaLibrary")
.filter(element -> element.getClassName().equals(MediaLibrary.class.getName())
&& element.getMethodName().equals("lastIndexOf"))
.count();
}
@@ -156,6 +122,7 @@ public class Tests {
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - not existing item - 10 Punkte")
public void testMediaLibraryLastIndexOfNotExisting() {
int points = 10;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for not existing item
@@ -175,6 +142,7 @@ public class Tests {
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - existing item - 5 Punkte")
public void testMediaLibraryLastIndexOfExisting() {
int points = 5;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for existing item
@@ -197,6 +165,7 @@ public class Tests {
@Test(name = "Aufgabe 1 - MediaLibrary - lastIndexOf - shifted start - 10 Punkte")
public void testMediaLibraryLastIndexOfShiftedStart() {
int points = 10;
TraceableMediaLibrary mediaLibrary = createTraceableMediaLibrary();
// test for shifted start
@@ -216,6 +185,8 @@ public class Tests {
addPoints(points);
}
// Aufgabe 2 - Deque tests - 50 Punkte
@Test(name = "Aufgabe 2 - Deque - addFirst - valid values - 10 Punkte")
public void testDequeAddFirst() {
int points = 10;
@@ -244,6 +215,7 @@ public class Tests {
@Test(name = "Aufgabe 2 - Deque - addFirst - null value - 3 Punkte")
public void testDequeAddFirstNull() {
int points = 3;
Deque deque = new Deque();
deque.addFirst(null);
if (getFront(deque) != null || getBack(deque) != null) {
@@ -257,6 +229,7 @@ public class Tests {
@Test(name = "Aufgabe 2 - Deque - addFirst - empty value - 2 Punkte")
public void testDequeAddFirstEmpty() {
int points = 2;
Deque deque = new Deque();
deque.addFirst("");
if (getFront(deque) != null || getBack(deque) != null) {
@@ -384,11 +357,19 @@ public class Tests {
@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.");
if (hasIllegalDequeFields()) {
points = 0;
TracingFramework.printError(
"Fields of Deque class were modified illegally. Cannot determine if field for size was added. Deducting all points for size tests.");
} else {
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);
@@ -421,122 +402,44 @@ public class Tests {
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 = getBackFromFront(deque);
return last != null ? last.getValue() : null;
}
private String peekFirstFromBack(Deque deque) {
Item first = getFrontFromBack(deque);
return first != null ? first.getValue() : null;
}
private Item getBackFromFront(Deque deque) {
Item current = getFront(deque);
while (current != null && current.getNext() != null) {
current = current.getNext();
}
return current;
}
private Item getFrontFromBack(Deque deque) {
Item current = getBack(deque);
while (current != null && current.getPrev() != null) {
current = current.getPrev();
}
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) {
/**
* Finds a method with the given name, return type, and parameter types in the
* specified class or its superclasses.
*
* @param clazz The class to search in.
* @param methodName The name of the method to find.
* @param returnType The return type of the method.
* @param parameterTypes The parameter types of the method.
* @return The method if found, null otherwise.
*/
public static Method findMethod(Class<?> clazz, String methodName, Class<?> returnType,
Class<?>... parameterTypes) {
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);
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
if (method.getReturnType().equals(returnType)) {
return method;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
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);
}
/**
* Checks if a class implements a given interface.
*
* @param clazz The class to check.
* @param interfaceClass The interface to check for.
* @return True if the class implements the interface, false otherwise.
*/
public static boolean implementsInterface(Class<?> clazz, Class<?> interfaceClass) {
Class<?>[] interfaces = clazz.getInterfaces();
return Arrays.stream(interfaces).anyMatch(interfaceClass::equals);
}
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);
}
}
/**
* START: MediaLibrary helper methods
*/
/**
* Sets the media library items.
@@ -544,7 +447,7 @@ public class Tests {
* @param mediaLibrary The media library.
* @param items The items.
*/
private void setItems(MediaLibrary mediaLibrary, MediaItem[] items) {
private static void setItems(MediaLibrary mediaLibrary, MediaItem[] items) {
try {
Field f = MediaLibrary.class.getDeclaredField("items");
f.setAccessible(true);
@@ -554,87 +457,6 @@ public class Tests {
}
}
/**
* 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 media library items via reflection.
*
@@ -651,4 +473,327 @@ public class Tests {
return new MediaItem[0];
}
}
/**
* END: MediaLibrary helper methods
*/
/**
* START: Deque helper methods
*/
/**
* Checks if the Deque class has illegal fields.
* The Deque class should only have two fields: 'front' and 'back', both of type
* Item.
*
* Check to be used in tests to ensure no extra fields are added.
*
* Size is supposed to be determined by iterating through the items, not by a
* field. Because given methods don't make use of such a field.
*
* @return True if illegal fields are found, false otherwise.
*/
public boolean hasIllegalDequeFields() {
Field[] fields = Deque.class.getDeclaredFields();
if (fields.length != 2) {
TracingFramework.printError("Deque class should have exactly 2 fields. But has: " + fields.length);
return true;
}
for (Field field : fields) {
String fieldName = field.getName();
if (fieldName.equals("front") || fieldName.equals("back")) {
if (!field.getType().equals(Item.class)) {
TracingFramework.printError("Field " + fieldName + " should be of type Item.");
return true;
}
} else {
TracingFramework.printError("Deque class has an illegal field: " + fieldName);
return true;
}
}
return false;
}
/**
* Builds a deque from the given values.
*
* @param values The values to add.
* @return The built deque.
*/
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;
}
/**
* Removes and returns the first element of the deque.
*
* @param deque The deque to poll from.
* @return The value of the first element, or null if the deque is empty.
*/
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;
}
/**
* Peeks at the first element of the deque without removing it.
*
* @param deque The deque to peek from.
* @return The value of the first element, or null if the deque is empty.
*/
private String peekFirst(Deque deque) {
Item first = getFront(deque);
return first != null ? first.getValue() : null;
}
/**
* Peeks at the last element of the deque without removing it.
*
* @param deque The deque to peek from.
* @return The value of the last element, or null if the deque is empty.
*/
private String peekLast(Deque deque) {
Item last = getBack(deque);
return last != null ? last.getValue() : null;
}
/**
* Peeks at the first element of the deque by traversing from the back.
*
* @param deque The deque to peek from.
* @return The value of the first element, or null if the deque is empty.
*/
private String peekFirstFromBack(Deque deque) {
Item first = getFrontFromBack(deque);
return first != null ? first.getValue() : null;
}
/**
* Gets the first item by traversing from the back.
*
* @param deque The deque to get the first item from.
* @return The first item, or null if the deque is empty.
*/
private Item getFrontFromBack(Deque deque) {
Item current = getBack(deque);
while (current != null && current.getPrev() != null) {
current = current.getPrev();
}
return current;
}
/**
* Gets the front item of the deque.
*
* @param deque The deque to get the front item from.
* @return The front item, or null if the deque is empty.
*/
private Item getFront(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getFront method", e);
}
}
/**
* Gets the back item of the deque.
*
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
private Item getBack(Deque deque) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
return (Item) field.get(deque);
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
}
/**
* Sets the front item of the deque.
*
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, front);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting front item", e);
}
}
/**
* Sets the back item of the deque.
*
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, back);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting back item", e);
}
}
/**
* Sets the next item for the given item.
*
* @param item The item to set the next item for.
* @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 (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting next item", e);
}
}
/**
* Sets the previous item for the given item.
*
* @param item The item to set the previous item for.
* @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 (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting previous item", e);
}
}
/**
* END: Deque helper methods
*/
/**
* 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);
}
/**
* 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 {
Class<Tests> clazz = Tests.class;
Tests test = new Tests();
System.out.println(String.format("Running tests for: %s", TESTAT_NAME));
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()));
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+52 -1
View File
@@ -1,3 +1,4 @@
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
@@ -7,6 +8,7 @@ import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Iterator;
public class InMemoryPath implements Path {
@@ -130,8 +132,9 @@ public class InMemoryPath implements Path {
}
StringBuilder sb = new StringBuilder();
for (int i = beginIndex + 1; i <= endIndex; i++) { // +1 because parts[0] is empty
if (!sb.isEmpty())
if (sb.length() != 0) {
sb.append("/");
}
sb.append(parts[i]);
}
return new InMemoryPath(fileSystem, sb.toString());
@@ -172,4 +175,52 @@ public class InMemoryPath implements Path {
return path.hashCode();
}
@Override
public boolean startsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'startsWith'");
}
@Override
public boolean endsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'endsWith'");
}
@Override
public Path resolve(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolve'");
}
@Override
public Path resolveSibling(Path other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public Path resolveSibling(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public File toFile() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'toFile'");
}
@Override
public WatchKey register(WatchService watcher, Kind<?>... events) throws IOException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'register'");
}
@Override
public Iterator<Path> iterator() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'iterator'");
}
}
@@ -1,7 +1,5 @@
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class InMemoryPathFactory {
+56
View File
@@ -1,10 +1,35 @@
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
System.out.println();
System.out.println("=========================================");
System.out.println("Aufgabe 1 - Baum");
System.out.println("=========================================");
System.out.println();
System.out.println("Creating tree with 4 nodes: 2, 1, 3, 1");
Tree tree = new Tree();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(1);
TreeVisitor v = new TreeVisitor();
// pre-order traversal
tree.traverse(v);
System.out.println("Visiting all nodes in pre-order.");
System.out.println("Expected output: [2.0, 1.0, 1.0, 3.0]");
System.out.println("Actual output: " + v);
// count
System.out.println("Node count of 2 should be 1 and was " + tree.count(2));
System.out.println("Node count of 1 should be 2 and was " + tree.count(1));
// height
System.out.println("Height of the tree should be 3 and was " + tree.height());
System.out.println();
System.out.println("=========================================");
@@ -46,6 +71,8 @@ public class Main {
"In his arms, the child was dead.",
"- Johann Wolfgang von Goethe, 1782");
// WARNING: Reading depends on writing!
System.out.println("Writing 'Erlking' data to memory path: " + erlkingPath);
serializer.write(erlkingPath, erlkingData);
System.out.println("Wrote 'Erlking' data to memory path.");
@@ -67,5 +94,34 @@ public class Main {
System.out.println("Aufgabe 3 - Exceptions");
System.out.println("=========================================");
System.out.println();
Deque deque = new Deque();
// getFirst
System.out.println("Checking if getFirst on empty deque throws NoSuchElementException");
try {
deque.getFirst();
System.out.println("FAILURE: No exception thrown.");
} catch (NoSuchElementException e) {
System.out.println("SUCCESS: NoSuchElementException thrown.");
} catch (Exception e) {
System.out.println("FAILURE: Unexpected exception thrown. Exception thrown: " + e.getClass().getName());
System.out.println(e.getMessage());
}
System.out.println();
// addLast
System.out.println("Checking if addLast(null) throws IllegalArgumentException");
try {
deque.addLast(null);
System.out.println("FAILURE: No exception thrown.");
} catch (IllegalArgumentException e) {
System.out.println("SUCCESS: IllegalArgumentException thrown.");
} catch (Exception e) {
System.out.println("FAILURE: Unexpected exception thrown. Exception thrown: " + e.getClass().getName());
System.out.println(e.getMessage());
}
}
}
@@ -1,3 +1,5 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -16,6 +18,12 @@ public class StringListSerializer {
*/
public void write(Path path, List<String> list) {
// TODO: implement
try {
Files.write(path, list);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
+239 -351
View File
@@ -7,7 +7,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -15,23 +14,22 @@ import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFram
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
private static final String TESTAT_NAME = "Testat 3A";
// Aufgabe 1 - Tree - 60 Punkte
@Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte")
public void testTreeTraverse() {
Method method = findMethod(Tree.class, "traverse", TreeVisitor.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.traverse(TreeVisitor) not found. Class was mutated illegally."));
int points = 20;
double[] values = new double[] { 3, 1, 5, 0, 2, 4, 6 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// pre-order
double[] expect = new double[] { 3, 1, 0, 2, 5, 4, 6 };
TreeVisitor visitor = new TreeVisitor();
if (!safeExecuteVoidMethod(method, tree, visitor)) {
throw new RuntimeException("Method Tree.traverse(TreeVisitor) did not execute successfully.");
}
tree.traverse(visitor);
double[] actual = visitor.toArray();
if (!Arrays.equals(actual, expect)) {
@@ -55,25 +53,18 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - count existing once - 10 Punkte")
public void testTreeCountExisitingOnce() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 3 should be found once
Optional<Integer> count = executeMethod(method, tree, Integer.class, 3);
int count = tree.count(3);
if (count.isEmpty()) {
if (count != 1) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(3) led to an execution. Deducting 10 points.");
} else if (count.get() != 1) {
points -= 10;
TracingFramework.printError("Tree.count(3) should return 1 , but was " + count.get());
TracingFramework.printError("Tree.count(3) should return 1 , but was " + count);
}
addPoints(points);
@@ -81,24 +72,18 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - count non exisiting - 10 Punkte")
public void testTreeCountNonExisiting() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
Optional<Integer> count = executeMethod(method, tree, Integer.class, 7);
int count = tree.count(7);
if (count.isEmpty()) {
if (count != 0) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(7) led to an execution. Deducting 10 points.");
} else if (count.get() != 0) {
points -= 10;
TracingFramework.printError("Tree.count(7) should return 0 , but was " + count.get());
TracingFramework.printError("Tree.count(7) should return 0 , but was " + count);
}
addPoints(points);
@@ -106,30 +91,24 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - count, should find once - 10 Punkte")
public void testTreeCountShouldFindOnce() {
Method method = findMethod(Tree.class, "count", double.class)
.orElseThrow(() -> new RuntimeException(
"Method Tree.count(double) not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
Optional<Integer> count = executeMethod(method, tree, Integer.class, 1);
int count = tree.count(1);
if (count.isEmpty()) {
points -= 10;
TracingFramework.printError("Execution of Tree.count(1) led to an execution. Deducting 10 points.");
} else if (count.get() == 2) {
if (count == 2) {
// correct, to nothing
} else if (count.get() == 3) {
} else if (count == 3) {
points -= 10;
TracingFramework
.printError("Tree.count(1) should return 2 with efficient implementation, but was " + count);
} else {
points -= 10;
TracingFramework.printError("Tree.count(1) should return 2 , but was " + count.get());
TracingFramework.printError("Tree.count(1) should return 2 , but was " + count);
}
addPoints(points);
@@ -137,41 +116,34 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - height - 10 Punkte")
public void testTreeHeight() {
Method method = findMethod(Tree.class, "height")
.orElseThrow(() -> new RuntimeException(
"Method Tree.height() not found. Class was mutated illegally."));
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
Optional<Integer> height = executeMethod(method, tree, Integer.class);
int height = tree.height();
if (height.isEmpty()) {
if (height != 3) {
points -= 10;
TracingFramework.printError("Execution of Tree.height() led to an execution. Deducting 10 points.");
} else if (height.get() != 3) {
points -= 10;
TracingFramework.printError("Tree.height() should return 3 , but was " + height.get());
TracingFramework.printError("Tree.height() should return 3 , but was " + height);
}
addPoints(points);
}
// Aufgabe 2 - IO - 20 Punkte
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
Method method = findMethod(StringListSerializer.class, "write", Path.class, List.class)
.orElseThrow(() -> new RuntimeException(
"Method StringListSerializer.write(Path, List) not found. Class was mutated illegally."));
int points = 10;
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/write.txt");
List<String> data = Arrays.asList("Hello", "World", "This is a test");
if (!safeExecuteVoidMethod(method, serializer, path, data)) {
throw new RuntimeException("Failed to execute StringListSerializer.write(Path, List) method.");
}
int points = 10;
serializer.write(path, data);
try {
List<String> content = Files.readAllLines(path);
if (!content.equals(data)) {
@@ -189,6 +161,7 @@ public class Tests {
@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");
@@ -215,6 +188,14 @@ public class Tests {
@Test(name = "Aufgabe 2 - IO - read - forced IOException - 5 Punkte")
public void testIOReadForcedIOException() {
int points = 5;
if (alwaysEmptyRead()) {
TracingFramework.printError(
"Reading from non-empty file returns empty list. Assuming read always returns empty list. Deducting 5 points.");
addPoints(0);
return;
}
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/forcedIOException.txt");
try {
@@ -246,13 +227,12 @@ public class Tests {
addPoints(points);
}
// Aufgabe 3 - Deque - 20 Punkte
@Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte")
public void testDequeAddFirstNull() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 3;
if (addFirstAlwaysException()) {
points -= 3;
TracingFramework.printError(
@@ -260,7 +240,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeVoidMethod(method, deque, (Object) null);
deque.addFirst(null);
points -= 3;
TracingFramework
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 3 points.");
@@ -279,16 +259,14 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst empty - 3 Punkte")
public void testDequeAddFirstEmpty() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 3;
if (addFirstAlwaysException()) {
points -= 3;
TracingFramework.printError(
@@ -296,7 +274,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeVoidMethod(method, deque, "");
deque.addFirst("");
points -= 3;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 3 points.");
@@ -315,16 +293,21 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst throws IllegalArgumentException - 2 Punkte")
public void testDequeAddFirstThrowsIllegalArgumentException() {
Method method = findMethod(Deque.class, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
int points = 2;
Method method = findMethod(Deque.class, "addFirst", String.class);
if (method == null) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
@@ -347,11 +330,8 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - addLast null - 3 Punkte")
public void testDequeAddLastNull() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 3;
if (addLastAlwaysException()) {
points -= 3;
TracingFramework.printError(
@@ -359,7 +339,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeVoidMethod(method, deque, (Object) null);
deque.addLast(null);
points -= 3;
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 3 points.");
@@ -378,16 +358,14 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast empty - 3 Punkte")
public void testDequeAddLastEmpty() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 3;
if (addLastAlwaysException()) {
points -= 3;
TracingFramework.printError(
@@ -395,7 +373,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeVoidMethod(method, deque, "");
deque.addLast("");
points -= 3;
TracingFramework
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 3 points.");
@@ -419,12 +397,15 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - addLast throws IllegalArgumentException - 2 Punkte")
public void testDequeAddLastThrowsIllegalArgumentException() {
Method method = findMethod(Deque.class, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
int points = 2;
Method method = findMethod(Deque.class, "addLast", String.class);
if (method == null) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
@@ -448,11 +429,8 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - getFirst empty exception - 2 Punkte")
public void testDequeGetFirstEmptyDeque() {
Method method = findMethod(Deque.class, "getFirst")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
int points = 2;
if (getFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
@@ -460,7 +438,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeMethod(method, deque, String.class, new Object[] {});
deque.getFirst();
points -= 2;
TracingFramework
.printError(
@@ -480,17 +458,21 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst throws NoSuchElementException - 2 Punkte")
public void testDequeGetFirstThrowsNoSuchElementException() {
Method method = findMethod(Deque.class, "getFirst")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
int points = 2;
Method method = findMethod(Deque.class, "getFirst");
if (method == null) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
@@ -514,11 +496,8 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - getLast empty exception - 2 Punkte")
public void testDequeGetLastEmptyDeque() {
Method method = findMethod(Deque.class, "getLast")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
int points = 2;
if (getLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
@@ -526,7 +505,7 @@ public class Tests {
} else {
try {
Deque deque = new Deque();
executeMethod(method, deque, String.class, new Object[] {});
deque.getLast();
points -= 2;
TracingFramework
.printError(
@@ -551,12 +530,15 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - getLast throws NoSuchElementException - 2 Punkte")
public void testDequeGetLastThrowsNoSuchElementException() {
Method method = findMethod(Deque.class, "getLast")
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
int points = 2;
Method method = findMethod(Deque.class, "getLast");
if (method == null) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
@@ -578,6 +560,89 @@ public class Tests {
addPoints(points);
}
/**
* Checks if reading from a non-empty file always returns an empty list.
*
* @return True if reading always returns an empty list, false otherwise.
*/
private boolean alwaysEmptyRead() {
Path path = InMemoryPathFactory.createPath("/test/foo.txt");
List<String> content = Arrays.asList("This", "is", "not", "empty");
try {
Files.write(path, content);
} catch (IOException e) {
return false;
}
StringListSerializer serializer = new StringListSerializer();
try {
List<String> readData = serializer.read(path);
return readData != null && readData.isEmpty();
} catch (Exception e) {
return false;
}
}
/**
* 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.");
}
}
/**
* Finds a method in a class by name and parameter types.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @param parameterTypes The parameter types of the method.
* @return The found method, or null if not found.
*/
public static Method findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return clazz.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* START: Deque helper methods
*/
/**
* Checks if addFirst throws any exception when called.
*
@@ -588,10 +653,7 @@ public class Tests {
*/
private boolean addFirstAlwaysException() {
Deque deque = new Deque();
Consumer<String> adder = findConsumer(deque, "addFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addFirst(String) not found. Class was mutated illegally."));
return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo");
return adderThrowsAnyException(deque::addFirst, "A", "BCDEF", "Hallo");
}
/**
@@ -604,10 +666,7 @@ public class Tests {
*/
private boolean addLastAlwaysException() {
Deque deque = new Deque();
Consumer<String> adder = findConsumer(deque, "addLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.addLast(String) not found. Class was mutated illegally."));
return adderThrowsAnyException(adder, "A", "BCDEF", "Hallo");
return adderThrowsAnyException(deque::addLast, "A", "BCDEF", "Hallo");
}
/**
@@ -640,13 +699,8 @@ public class Tests {
*/
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
Supplier<String> getter = findSupplier(deque, "getFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.getFirst() not found. Class was mutated illegally."));
Supplier<String> poller = findSupplier(deque, "pollFirst", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.pollFirst() not found. Class was mutated illegally."));
return getterAnyThrowsException(getter, poller, 5);
// should be executable five times when deque is not empty
return getterThrowsAnyException(deque::getFirst, deque::pollFirst, 5);
}
/**
@@ -661,13 +715,7 @@ public class Tests {
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
Supplier<String> getter = findSupplier(deque, "getLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.getLast() not found. Class was mutated illegally."));
Supplier<String> poller = findSupplier(deque, "pollLast", String.class)
.orElseThrow(() -> new RuntimeException(
"Method Deque.pollLast() not found. Class was mutated illegally."));
return getterAnyThrowsException(getter, poller, 5);
return getterThrowsAnyException(deque::getLast, deque::pollLast, 5);
}
/**
@@ -679,7 +727,7 @@ public class Tests {
* @param n The number of times to call the methods.
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getterAnyThrowsException(Supplier<String> getter, Supplier<String> poller, int n) {
private boolean getterThrowsAnyException(Supplier<String> getter, Supplier<String> poller, int n) {
try {
for (int i = 0; i < n; i++) {
getter.get();
@@ -727,97 +775,57 @@ public class Tests {
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
* Gets the back item of the deque.
*
* @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.
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
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.");
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
}
/**
* Sets the next item in an Item using reflection.
* Sets the front item of the deque.
*
* @param item The item.
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, front);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting front item", e);
}
}
/**
* Sets the back item of the deque.
*
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, back);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting back item", e);
}
}
/**
* Sets the next item for the given item.
*
* @param item The item to set the next item for.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
@@ -825,15 +833,15 @@ public class Tests {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
field.set(item, next);
} catch (Exception e) {
throw new RuntimeException("Failed to set next.");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting next item", e);
}
}
/**
* Sets the previous item in an Item using reflection.
* Sets the previous item for the given item.
*
* @param item The item.
* @param item The item to set the previous item for.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
@@ -841,141 +849,19 @@ public class Tests {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);
field.set(item, prev);
} catch (Exception e) {
throw new RuntimeException("Failed to set prev.");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting previous item", e);
}
}
/**
* General utility methods below...
* END: Deque helper methods
*/
/**
* Finds a method in a class by name and parameter types.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @param parameterTypes The parameter types of the method.
* @return An Optional containing the found method, or empty if not found.
*/
public static Optional<Method> findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return Optional.of(clazz.getDeclaredMethod(name, parameterTypes));
} catch (NoSuchMethodException e) {
return Optional.empty();
}
}
/**
* Checks if a method has a specific return type.
*
* @param method The method to check.
* @param returnType The expected return type.
* @return True if the method has the expected return type, false otherwise.
*/
public static boolean hasReturnType(Method method, Class<?> returnType) {
return method.getReturnType().equals(returnType);
}
public static <T> Optional<T> executeMethod(Method method, Object instance, Class<T> returnType, Object... args) {
try {
Object result = method.invoke(instance, args);
return Optional.of(returnType.cast(result));
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
}
public static void executeVoidMethod(Method method, Object instance, Object... args) throws Exception {
method.invoke(instance, args);
}
public static boolean safeExecuteVoidMethod(Method method, Object instance, Object... args) {
try {
executeVoidMethod(method, instance, args);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Converts a reference type to its primitive value if applicable.
* If the object is a boxed primitive and the target type is a primitive,
* returns the primitive value. Otherwise, returns the object as is.
*
* @param value The object to convert.
* @param primitiveType The target primitive class (e.g., int.class,
* double.class).
* @return The primitive value or the original object.
*/
public static Object toPrimitiveIfPossible(Object value, Class<?> primitiveType) {
if (value == null) {
return null;
}
if (primitiveType == int.class && value instanceof Integer) {
return ((Integer) value).intValue();
} else if (primitiveType == double.class && value instanceof Double) {
return ((Double) value).doubleValue();
} else if (primitiveType == boolean.class && value instanceof Boolean) {
return ((Boolean) value).booleanValue();
} else if (primitiveType == long.class && value instanceof Long) {
return ((Long) value).longValue();
} else if (primitiveType == float.class && value instanceof Float) {
return ((Float) value).floatValue();
} else if (primitiveType == short.class && value instanceof Short) {
return ((Short) value).shortValue();
} else if (primitiveType == byte.class && value instanceof Byte) {
return ((Byte) value).byteValue();
} else if (primitiveType == char.class && value instanceof Character) {
return ((Character) value).charValue();
}
return value;
}
/**
* Finds a consumer method in a class by name and parameter type.
*
* @param <T> The type of the parameter for the consumer.
* @param obj The object to search in.
* @param methodName The name of the method.
* @param parameterType The parameter type of the method.
* @return An Optional containing the found consumer, or empty if not found.
*/
public static <T> Optional<Consumer<T>> findConsumer(Object obj, String methodName, Class<T> parameterType) {
Optional<Method> method = findMethod(obj.getClass(), methodName, parameterType);
if (method.isEmpty()) {
return Optional.empty();
}
return Optional.of(arg -> safeExecuteVoidMethod(method.get(), obj, toPrimitiveIfPossible(arg, parameterType)));
}
/**
* Finds a supplier method in a class by name and return type.
*
* @param <T> The type of the return value for the supplier.
* @param obj The object to search in.
* @param methodName The name of the method.
* @param returnType The expected return type of the method.
* @return An Optional containing the found supplier, or empty if not found.
*/
public static <T> Optional<Supplier<T>> findSupplier(Object obj, String methodName, Class<T> returnType) {
Optional<Method> method = findMethod(obj.getClass(), methodName);
if (method.isEmpty()) {
return Optional.empty();
}
return Optional.of(() -> {
Optional<T> result = executeMethod(method.get(), obj, returnType);
return result.orElse(null);
});
}
/**
* The points of each test case.
*/
private java.util.List<Integer> points = new ArrayList<>();
private List<Integer> testPoints = new ArrayList<>();
/**
* This method will be called by jack after all test have been executed to get
@@ -985,7 +871,7 @@ public class Tests {
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
for (Integer p : testPoints) {
sum += p;
}
return sum;
@@ -998,7 +884,7 @@ public class Tests {
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
testPoints.add(value);
}
/**
@@ -1009,31 +895,33 @@ public class Tests {
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Class<Tests> clazz = Tests.class;
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println(String.format("Running tests for: %s", TESTAT_NAME));
System.out.println();
for (Method method : test.getClass().getMethods()) {
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
System.out.println(String.format("Currently testing: %s", method.getName()));
int size = test.testPoints.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.");
if (test.testPoints.size() != size + 1) {
System.err.println("ERROR: Test yields no or multiple results. Erroneous test.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
System.out.println(
String.format("PASS: Test passed with %d points!",
test.testPoints.get(test.testPoints.size() - 1)));
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
System.err.println(String.format("ERROR: Test failed with exception: %s", e.getMessage()));
e.printStackTrace();
}
System.out.println();
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
System.out.println(String.format("Total points: %d", test.getResult()));
}
public static void main(String[] args) {
+9 -11
View File
@@ -9,17 +9,17 @@ 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
@@ -30,7 +30,7 @@ public class TreeNode {
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
@@ -39,7 +39,7 @@ public class TreeNode {
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
@@ -48,7 +48,7 @@ public class TreeNode {
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
@@ -57,7 +57,7 @@ public class TreeNode {
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
@@ -66,7 +66,7 @@ public class TreeNode {
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
@@ -75,7 +75,5 @@ public class TreeNode {
public void setRight(TreeNode right) {
this.right = right;
}
}
+52 -1
View File
@@ -1,3 +1,4 @@
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
@@ -7,6 +8,7 @@ import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Iterator;
public class InMemoryPath implements Path {
@@ -130,8 +132,9 @@ public class InMemoryPath implements Path {
}
StringBuilder sb = new StringBuilder();
for (int i = beginIndex + 1; i <= endIndex; i++) { // +1 because parts[0] is empty
if (!sb.isEmpty())
if (sb.length() != 0) {
sb.append("/");
}
sb.append(parts[i]);
}
return new InMemoryPath(fileSystem, sb.toString());
@@ -172,4 +175,52 @@ public class InMemoryPath implements Path {
return path.hashCode();
}
@Override
public boolean startsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'startsWith'");
}
@Override
public boolean endsWith(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'endsWith'");
}
@Override
public Path resolve(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolve'");
}
@Override
public Path resolveSibling(Path other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public Path resolveSibling(String other) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'resolveSibling'");
}
@Override
public File toFile() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'toFile'");
}
@Override
public WatchKey register(WatchService watcher, Kind<?>... events) throws IOException {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'register'");
}
@Override
public Iterator<Path> iterator() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'iterator'");
}
}
+2 -17
View File
@@ -1,30 +1,15 @@
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 static final InMemoryFileSystemProvider provider = new InMemoryFileSystemProvider();
private static final InMemoryFileSystem fileSystem = new InMemoryFileSystem(provider);
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
*
@@ -1 +0,0 @@
InMemoryFileSystemProvider
+1 -1
View File
@@ -122,6 +122,6 @@ public class Main {
System.out.println("FAILURE: Unexpected exception thrown. Exception thrown: " + e.getClass().getName());
System.out.println(e.getMessage());
}
}
}
+3 -2
View File
@@ -1,4 +1,5 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -16,7 +17,6 @@ public class StringListSerializer {
*/
public void write(Path path, List<String> list) {
// TODO: implement
}
/**
@@ -27,6 +27,7 @@ public class StringListSerializer {
*/
public List<String> read(Path path) {
// TODO: implement
return Arrays.asList("Not", "implemented", "yet");
return new ArrayList<>();
}
}
+346 -231
View File
@@ -15,9 +15,14 @@ import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFram
public class Tests {
private static final String TESTAT_NAME = "Testat 3B";
// Aufgabe 1 - Tree - 60 Punkte
@Test(name = "Aufgabe 1 - Tree - traverse - 20 Punkte")
public void testTreeTraverse() {
int points = 20;
double[] values = new double[] { 3, 5, 1, 6, 4, 2, 0 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
@@ -46,39 +51,64 @@ public class Tests {
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count - 30 Punkte")
public void testTreeCount() {
int points = 0;
@Test(name = "Aufgabe 1 - Tree - count existing once - 10 Punkte")
public void testTreeCountExisitingOnce() {
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 5, 1, 1, 4, 2, 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);
if (count != 1) {
points -= 10;
TracingFramework.printError("Tree.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);
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count non exisiting - 10 Punkte")
public void testTreeCountNonExisiting() {
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 5, 1, 1, 4, 2, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
int count = tree.count(7);
if (count != 0) {
points -= 10;
TracingFramework.printError("Tree.count(7) should return 0 , but was " + count);
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
addPoints(points);
}
@Test(name = "Aufgabe 1 - Tree - count, should find once - 10 Punkte")
public void testTreeCountShouldFindOnce() {
int points = 10;
// non-sorted tree
double[] values = new double[] { 3, 5, 1, 1, 4, 2, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
int count = tree.count(1);
if (count == 2) {
points += 15;
// correct, to nothing
} else if (count == 3) {
points += 8;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
points -= 10;
TracingFramework
.printError("Tree.count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
points -= 10;
TracingFramework.printError("Tree.count(1) should return 2 , but was " + count);
}
addPoints(points);
@@ -86,29 +116,34 @@ public class Tests {
@Test(name = "Aufgabe 1 - Tree - height - 10 Punkte")
public void testTreeHeight() {
int points = 0;
int points = 10;
// 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 {
if (height != 3) {
points -= 10;
TracingFramework.printError("Height should return 3 , but was " + height);
}
addPoints(points);
}
// Aufgabe 2 - IO - 20 Punkte
@Test(name = "Aufgabe 2 - IO - write - 10 Punkte")
public void testIOWrite() {
int points = 10;
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)) {
@@ -126,6 +161,7 @@ public class Tests {
@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");
@@ -152,6 +188,14 @@ public class Tests {
@Test(name = "Aufgabe 2 - IO - read - forced IOException - 5 Punkte")
public void testIOReadForcedIOException() {
int points = 5;
if (alwaysEmptyRead()) {
TracingFramework.printError(
"Reading from non-empty file returns empty list. Assuming read always returns empty list. Deducting 5 points.");
addPoints(0);
return;
}
StringListSerializer serializer = new StringListSerializer();
Path path = InMemoryPathFactory.createPath("/test/forcedIOException.txt");
try {
@@ -183,20 +227,23 @@ public class Tests {
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst null - 2 Punkte")
// Aufgabe 3 - Deque - 20 Punkte
@Test(name = "Aufgabe 3 - Deque - addFirst null - 3 Punkte")
public void testDequeAddFirstNull() {
int points = 2;
int points = 3;
if (addFirstAlwaysException()) {
points -= 2;
points -= 3;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
Deque deque = new Deque();
deque.addFirst(null);
points -= 2;
points -= 3;
TracingFramework
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 2 points.");
.printError("Deque.addFirst(null) should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
@@ -212,23 +259,25 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst empty - 2 Punkte")
@Test(name = "Aufgabe 3 - Deque - addFirst empty - 3 Punkte")
public void testDequeAddFirstEmpty() {
int points = 2;
int points = 3;
if (addFirstAlwaysException()) {
points -= 2;
points -= 3;
TracingFramework.printError(
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
"Deque.addFirst(\"A\"), Deque.addFirst(\"BCDEF\"), or Deque.addFirst(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
Deque deque = new Deque();
deque.addFirst("");
points -= 2;
points -= 3;
TracingFramework
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 2 points.");
.printError("Deque.addFirst(\"\") should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
@@ -244,52 +293,56 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addFirst throws IllegalArgumentException - 2 Punkte")
public void testDequeAddFirstThrowsIllegalArgumentException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("addFirst", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
Method method = findMethod(Deque.class, "addFirst", String.class);
if (method == null) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addFirst(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
"Deque.addFirst(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addFirst(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast null - 2 Punkte")
@Test(name = "Aufgabe 3 - Deque - addLast null - 3 Punkte")
public void testDequeAddLastNull() {
int points = 2;
int points = 3;
if (addLastAlwaysException()) {
points -= 2;
points -= 3;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
Deque deque = new Deque();
deque.addLast(null);
points -= 2;
points -= 3;
TracingFramework
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 2 points.");
.printError("Deque.addLast(null) should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
@@ -305,23 +358,25 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - addLast empty - 2 Punkte")
@Test(name = "Aufgabe 3 - Deque - addLast empty - 3 Punkte")
public void testDequeAddLastEmpty() {
int points = 2;
int points = 3;
if (addLastAlwaysException()) {
points -= 2;
points -= 3;
TracingFramework.printError(
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 2 points.");
"Deque.addLast(\"A\"), Deque.addLast(\"BCDEF\"), or Deque.addLast(\"Hallo\") threw an exception. Assuming method always throws an exception on valid values. Deducting 3 points.");
} else {
try {
Deque deque = new Deque();
deque.addLast("");
points -= 2;
points -= 3;
TracingFramework
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 2 points.");
.printError("Deque.addLast(\"\") should throw an exception, but did not. Deducting 3 points.");
} catch (Exception e) {
if (!(e instanceof IllegalArgumentException)) {
points -= 1;
@@ -343,35 +398,39 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - addLast throws IllegalArgumentException - 2 Punkte")
public void testDequeAddLastThrowsIllegalArgumentException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("addLast", String.class);
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
Method method = findMethod(Deque.class, "addLast", String.class);
if (method == null) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(String) should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.addLast(String) should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != IllegalArgumentException.class) {
points -= 2;
TracingFramework.printError(
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
"Deque.addLast(String) should throw an IllegalArgumentException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.addLast(String) not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst empty exception - 2 Punkte")
public void testDequeGetFirstEmptyDeque() {
int points = 2;
if (getFirstAlwaysException()) {
points -= 2;
TracingFramework.printError(
@@ -399,41 +458,46 @@ public class Tests {
}
}
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getFirst throws NoSuchElementException - 2 Punkte")
public void testDequeGetFirstThrowsNoSuchElementException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("getFirst");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
Method method = findMethod(Deque.class, "getFirst");
if (method == null) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getFirst() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
"Deque.getFirst() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.getFirst() not found. Class was mutated illegally.");
}
addPoints(points);
}
@Test(name = "Aufgabe 3 - Deque - getLast empty exception - 2 Punkte")
public void testDequeGetLastEmptyDeque() {
int points = 2;
if (getLastAlwaysException()) {
points -= 2;
TracingFramework.printError(
@@ -467,32 +531,118 @@ public class Tests {
@Test(name = "Aufgabe 3 - Deque - getLast throws NoSuchElementException - 2 Punkte")
public void testDequeGetLastThrowsNoSuchElementException() {
int points = 2;
try {
Method method = Deque.class.getDeclaredMethod("getLast");
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
Method method = findMethod(Deque.class, "getLast");
if (method == null) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
addPoints(0);
return;
}
Class<?>[] exceptionTypes = method.getExceptionTypes();
if (exceptionTypes.length == 0) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw an exception, but did not. Deducting 2 point.");
} else if (exceptionTypes.length != 1) {
points -= 2;
TracingFramework.printError("Deque.getLast() should only throw one exception, but threw: "
+ Arrays.toString(exceptionTypes) + ". Deducting 2 points.");
} else {
if (exceptionTypes[0] != NoSuchElementException.class) {
points -= 2;
TracingFramework.printError(
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
"Deque.getLast() should throw a NoSuchElementException, but threw: "
+ exceptionTypes[0].getName() + ". Deducting 2 points.");
}
} catch (NoSuchMethodException e) {
TracingFramework.printError("Method Deque.getLast() not found. Class was mutated illegally.");
}
addPoints(points);
}
/**
* Checks if reading from a non-empty file always returns an empty list.
*
* @return True if reading always returns an empty list, false otherwise.
*/
private boolean alwaysEmptyRead() {
Path path = InMemoryPathFactory.createPath("/test/foo.txt");
List<String> content = Arrays.asList("This", "is", "not", "empty");
try {
Files.write(path, content);
} catch (IOException e) {
return false;
}
StringListSerializer serializer = new StringListSerializer();
try {
List<String> readData = serializer.read(path);
return readData != null && readData.isEmpty();
} catch (Exception e) {
return false;
}
}
/**
* 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.");
}
}
/**
* Finds a method in a class by name and parameter types.
*
* @param clazz The class to search in.
* @param name The name of the method.
* @param parameterTypes The parameter types of the method.
* @return The found method, or null if not found.
*/
public static Method findMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return clazz.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* START: Deque helper methods
*/
/**
* Checks if addFirst throws any exception when called.
*
@@ -533,9 +683,9 @@ public class Tests {
adder.accept(value);
}
} catch (Exception e) {
return true;
return false;
}
return false;
return true;
}
/**
@@ -550,7 +700,7 @@ public class Tests {
private boolean getFirstAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterAnyThrowsException(deque::getFirst, deque::pollFirst, 5);
return getterThrowsAnyException(deque::getFirst, deque::pollFirst, 5);
}
/**
@@ -565,7 +715,7 @@ public class Tests {
private boolean getLastAlwaysException() {
Deque deque = buildDeque("A", "B", "C", "D", "E");
// should be executable five times when deque is not empty
return getterAnyThrowsException(deque::getLast, deque::pollLast, 5);
return getterThrowsAnyException(deque::getLast, deque::pollLast, 5);
}
/**
@@ -577,7 +727,7 @@ public class Tests {
* @param n The number of times to call the methods.
* @return True if the getter throws any exception, false otherwise.
*/
private boolean getterAnyThrowsException(Supplier<String> getter, Supplier<String> poller, int n) {
private boolean getterThrowsAnyException(Supplier<String> getter, Supplier<String> poller, int n) {
try {
for (int i = 0; i < n; i++) {
getter.get();
@@ -625,97 +775,57 @@ public class Tests {
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
* Gets the back item of the deque.
*
* @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.
* @param deque The deque to get the back item from.
* @return The back item, or null if the deque is empty.
*/
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.");
} catch (IllegalAccessException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException("Error accessing getBack method", e);
}
}
/**
* Sets the next item in an Item using reflection.
* Sets the front item of the deque.
*
* @param item The item.
* @param deque The deque to set the front item for.
* @param front The front item to set.
*/
private void setFront(Deque deque, Item front) {
try {
Field field = Deque.class.getDeclaredField("front");
field.setAccessible(true);
field.set(deque, front);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting front item", e);
}
}
/**
* Sets the back item of the deque.
*
* @param deque The deque to set the back item for.
* @param back The back item to set.
*/
private void setBack(Deque deque, Item back) {
try {
Field field = Deque.class.getDeclaredField("back");
field.setAccessible(true);
field.set(deque, back);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting back item", e);
}
}
/**
* Sets the next item for the given item.
*
* @param item The item to set the next item for.
* @param next The next item to set.
*/
private void setNext(Item item, Item next) {
@@ -723,15 +833,15 @@ public class Tests {
Field field = Item.class.getDeclaredField("next");
field.setAccessible(true);
field.set(item, next);
} catch (Exception e) {
throw new RuntimeException("Failed to set next.");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting next item", e);
}
}
/**
* Sets the previous item in an Item using reflection.
* Sets the previous item for the given item.
*
* @param item The item.
* @param item The item to set the previous item for.
* @param prev The previous item to set.
*/
private void setPrev(Item item, Item prev) {
@@ -739,15 +849,19 @@ public class Tests {
Field field = Item.class.getDeclaredField("prev");
field.setAccessible(true);
field.set(item, prev);
} catch (Exception e) {
throw new RuntimeException("Failed to set prev.");
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException("Error setting previous item", e);
}
}
/**
* END: Deque helper methods
*/
/**
* The points of each test case.
*/
private java.util.List<Integer> points = new ArrayList<>();
private List<Integer> testPoints = new ArrayList<>();
/**
* This method will be called by jack after all test have been executed to get
@@ -757,7 +871,7 @@ public class Tests {
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
for (Integer p : testPoints) {
sum += p;
}
return sum;
@@ -770,7 +884,7 @@ public class Tests {
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
testPoints.add(value);
}
/**
@@ -781,32 +895,33 @@ public class Tests {
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Class<Tests> clazz = Tests.class;
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println(String.format("Running tests for: %s", TESTAT_NAME));
System.out.println();
for (Method method : test.getClass().getMethods()) {
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
System.out.println(String.format("Currently testing: %s", method.getName()));
int size = test.testPoints.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.");
if (test.testPoints.size() != size + 1) {
System.err.println("ERROR: Test yields no or multiple results. Erroneous test.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
System.out.println(
String.format("PASS: Test passed with %d points!",
test.testPoints.get(test.testPoints.size() - 1)));
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
System.err.println(String.format("ERROR: Test failed with exception: %s", e.getMessage()));
e.printStackTrace();
}
System.out.println("");
System.out.println();
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
System.out.println(String.format("Total points: %d", test.getResult()));
}
public static void main(String[] args) {
+1 -1
View File
@@ -107,7 +107,7 @@ public class Tree {
if (current == null)
return 0;
// TODO: implement
return -1;
return -42;
}
/**
+9 -11
View File
@@ -9,17 +9,17 @@ 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
@@ -30,7 +30,7 @@ public class TreeNode {
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
@@ -39,7 +39,7 @@ public class TreeNode {
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
@@ -48,7 +48,7 @@ public class TreeNode {
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
@@ -57,7 +57,7 @@ public class TreeNode {
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
@@ -66,7 +66,7 @@ public class TreeNode {
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
@@ -75,7 +75,5 @@ public class TreeNode {
public void setRight(TreeNode right) {
this.right = right;
}
}