Luleå University of Technology
LTU courses · Object-Oriented Programming in Java
Course D0010E
Advanced programming in Java: object-oriented design, algorithms, data structures, and software engineering. Labs added progressively as the course continues.
Lab 1: Arithmetic Quiz & Spellchecker
Two programs, one launcher
Main.java presents a menu to launch either the
Arithmetic quiz or the Spellchecker.
Both are fully interactive. Try them live below.
10 random questions covering +, −, ×, ÷. First correct answer earns 10 points, second attempt earns 5. Max score: 100.
10 questions, random operators. Answer correctly first try for 10 pts, second try for 5 pts.
public class ArithmeticProblem {
private final int operand1, operand2;
private final char operator;
public ArithmeticProblem(char op) {
if (op != '+' && op != '-' && op != '*' && op != '/')
throw new IllegalArgumentException("Operator is not legal.");
operator = op;
switch (operator) {
case '+':
operand1 = (int)(101 * Math.random());
operand2 = (int)((101 - operand1) * Math.random());
break;
case '-':
operand1 = 9 + (int)(92 * Math.random());
operand2 = (int)((1 + operand1) * Math.random());
break;
case '*':
operand1 = (int)(51 * Math.random());
operand2 = (int)(13 * Math.random());
break;
default: // '/'
int answer = (int)(13 * Math.random());
operand2 = 1 + (int)(12 * Math.random());
operand1 = operand2 * answer;
break;
}
}
public String getQuestion() {
return String.format("What is %d %s %d ?", operand1, operator, operand2);
}
public int getAnswer() {
switch (operator) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
default: return operand1 / operand2;
}
}
}
public class ArithmeticQuiz {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Arithmetic Quiz!");
int points = 0;
for (int i = 0; i < 10; i++) {
char[] ops = {'+', '-', '*', '/'};
char op = ops[(int)(Math.random() * 4)];
ArithmeticProblem problem = new ArithmeticProblem(op);
System.out.println("Question " + (i + 1) + ":");
System.out.println(problem.getQuestion());
int userAnswer = in.nextInt();
if (userAnswer == problem.getAnswer()) {
System.out.println("Correct! You get 10 points.");
points += 10;
} else {
System.out.println("Incorrect. Try again.");
System.out.println(problem.getQuestion());
userAnswer = in.nextInt();
if (userAnswer == problem.getAnswer()) {
System.out.println("Correct! You get 5 points.");
points += 5;
} else {
System.out.println("Incorrect. The correct answer is "
+ problem.getAnswer() + ".");
}
}
}
System.out.println("Your total points: " + points + " out of 100.");
}
}
Checks words against a 72,875-word dictionary. If misspelled, suggests corrections using five different algorithms.
public class Spellcheck {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
WordList wordList = new WordList();
System.out.println("Word list contains " + wordList.size() + " words.");
while (true) {
System.out.print("Enter a word (or 'exit'): ");
String input = in.nextLine().trim().toLowerCase();
if (input.equals("exit")) break;
if (wordList.contains(input))
System.out.println("'" + input + "' is spelled correctly.");
else {
System.out.println("'" + input + "' is NOT spelled correctly.");
System.out.println("Did you mean:");
delete_suggestion(input, wordList);
insert_suggestion(input, wordList);
swap_suggestion(input, wordList);
swap_suggestion2(input, wordList);
insert_space_suggestion(input, wordList);
}
}
}
// Delete one character at each position
static void delete_suggestion(String input, WordList wl) {
for (int i = 0; i < input.length(); i++) {
String s = input.substring(0,i) + input.substring(i+1);
if (wl.contains(s)) System.out.println(" - " + s);
}
}
// Insert every letter at every position
static void insert_suggestion(String input, WordList wl) {
for (char c = 'a'; c <= 'z'; c++)
for (int i = 0; i <= input.length(); i++) {
String s = input.substring(0,i) + c + input.substring(i);
if (wl.contains(s)) System.out.println(" - " + s);
}
}
// Replace each character with every other letter
static void swap_suggestion(String input, WordList wl) {
for (int i = 0; i < input.length(); i++)
for (char c = 'a'; c <= 'z'; c++) {
if (c == input.charAt(i)) continue;
String s = input.substring(0,i) + c + input.substring(i+1);
if (wl.contains(s)) System.out.println(" - " + s);
}
}
// Swap adjacent characters
static void swap_suggestion2(String input, WordList wl) {
for (int i = 0; i < input.length() - 1; i++) {
char[] arr = input.toCharArray();
char tmp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = tmp;
String s = new String(arr);
if (wl.contains(s)) System.out.println(" - " + s);
}
}
// Split into two valid words
static void insert_space_suggestion(String input, WordList wl) {
for (int i = 1; i < input.length(); i++) {
String a = input.substring(0,i), b = input.substring(i);
if (wl.contains(a) && wl.contains(b))
System.out.println(" - " + a + " " + b);
}
}
}
public class WordList {
private final String[] words;
public WordList() {
try {
URL listLocation = WordList.class.getClassLoader()
.getResource("unsorted_words.txt");
Scanner in = new Scanner(listLocation.openStream());
ArrayList<String> wordList = new ArrayList<>();
while (in.hasNextLine())
wordList.add(in.nextLine());
words = wordList.toArray(new String[0]);
in.close();
} catch (Exception e) {
throw new IllegalStateException("Can't load word list.");
}
}
public boolean contains(String lowerCaseWord) {
for (String s : words)
if (s.equals(lowerCaseWord)) return true;
return false;
}
public int size() { return words.length; }
public String get(int index) { return words[index]; }
}
Building ArrayList from scratch
MyArrayList<E> is a generic, resizable array list built to match Java's
real ArrayList API without using it. Implements
List<E>, Cloneable,
Serializable, and RandomAccess.
All 15 unit tests in MyArrayListTest.java pass.
Try the full implementation live: add, get, set, remove, indexOf, contains, clone, and more. Internally uses a dynamic array that doubles in size when full, exactly like the real Java ArrayList.
public class MyArrayList<E> implements List<E>, Cloneable, Serializable, RandomAccess {
private E[] array;
private int size;
private static final int DEFAULT_CAPACITY = 10;
// ── CONSTRUCTORS ──────────────────────────────────────────
public MyArrayList(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
array = (E[]) new Object[initialCapacity];
size = 0;
}
public MyArrayList() { this(DEFAULT_CAPACITY); }
// ── §1: BASIC INFO ────────────────────────────────────────
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void clear() {
for (int i = 0; i < size; i++) array[i] = null;
size = 0;
}
// ── §2: CAPACITY ──────────────────────────────────────────
public void ensureCapacity(int minCapacity) {
if (minCapacity > array.length) {
int newCap = Math.max(array.length * 2 + 1, minCapacity);
E[] newArr = (E[]) new Object[newCap];
for (int i = 0; i < size; i++) newArr[i] = array[i];
array = newArr;
}
}
public void trimToSize() {
if (size < array.length) {
E[] newArr = (E[]) new Object[size];
for (int i = 0; i < size; i++) newArr[i] = array[i];
array = newArr;
}
}
// ── §3: ADD ───────────────────────────────────────────────
public void add(int index, E element) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
ensureCapacity(size + 1);
for (int i = size; i > index; i--) array[i] = array[i - 1];
array[index] = element;
size++;
}
public boolean add(E e) { add(size, e); return true; }
// ── §4: READ / REPLACE ────────────────────────────────────
public E get(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return array[index];
}
public E set(int index, E element) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
E old = array[index];
array[index] = element;
return old;
}
// ── §5: REMOVE ────────────────────────────────────────────
public E remove(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
E removed = array[index];
removeRange(index, index + 1);
return removed;
}
protected void removeRange(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
throw new IndexOutOfBoundsException();
int count = toIndex - fromIndex;
for (int i = toIndex; i < size; i++) array[i - count] = array[i];
for (int i = size - count; i < size; i++) array[i] = null;
size -= count;
}
// ── §6: SEARCH ────────────────────────────────────────────
public int indexOf(Object o) {
for (int i = 0; i < size; i++)
if (o == null ? array[i] == null : o.equals(array[i])) return i;
return -1;
}
public boolean remove(Object o) {
int idx = indexOf(o);
if (idx == -1) return false;
remove(idx);
return true;
}
public boolean contains(Object o) { return indexOf(o) != -1; }
// ── §7: COPY ──────────────────────────────────────────────
public Object clone() {
MyArrayList<E> copy = new MyArrayList<>(size);
for (int i = 0; i < size; i++) copy.array[i] = array[i];
copy.size = this.size;
return copy;
}
public Object[] toArray() {
Object[] out = new Object[size];
for (int i = 0; i < size; i++) out[i] = array[i];
return out;
}
}
// Tests run with: java -ea Lab2.MyArrayListTest
// -ea enables Java assertions
public static void testAvAddindex() {
data = new MyArrayList<Integer>(100);
// negative index must throw
try { data.add(-1, null); }
catch (IndexOutOfBoundsException e) { /* expected */ }
data.add(0, 10); data.add(1, 11); data.add(2, 12);
data.add(1, 21); data.add(0, 20);
// list is now: [20, 10, 21, 11, 12]
assert data.get(0) == 20;
assert data.get(1) == 10;
assert data.get(2) == 21;
}
public static void testAvRemoveRange() {
data = new MyArrayList<Integer>();
insert(6); // [0, 1, 2, 3, 4, 5]
data.removeRange(2, 4); // removes 2, 3
// list is now: [0, 1, 4, 5]
assert data.contains(0) && data.contains(1);
assert !data.contains(2) && !data.contains(3);
assert data.contains(4) && data.contains(5);
}
public static void testAvClone() {
data = new MyArrayList<Integer>();
insert(3); // [0, 1, 2]
MyArrayList<Integer> clone = (MyArrayList<Integer>) data.clone();
// clone has same values
assert clone.get(0).equals(data.get(0));
// changing clone does NOT affect original (own array)
clone.set(1, 99);
assert !data.get(1).equals(99);
}
A Swing game with full MVC architecture
Navigate between coloured rooms connected by corridors using WASD keys.
Built with clean MVC: Nivå (model) extends Observable,
Målarduk (view) renders on a JPanel,
Tangentbordslyssnare (controller) handles keyboard input,
and GUI implements Observer to repaint on every move.
The canvas below is a pixel-accurate recreation of the actual Java Swing game.
Exact map from Huvudprogram.java, 8 rooms, 10 corridors.
Click the map then use WASD to navigate. Black dot = your position.
Click the canvas to focus it, then use WASD to move between rooms.
public class GUI extends JFrame implements Observer {
private Målarduk målarduk;
public GUI(Nivå enNivå) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enNivå.addObserver(this); // register so we repaint on level change
målarduk = new Målarduk(enNivå);
målarduk.setPreferredSize(new Dimension(800, 600));
målarduk.addKeyListener(new Tangentbordslyssnare(enNivå));
setContentPane(målarduk);
pack();
setLocationRelativeTo(null);
setVisible(true);
målarduk.requestFocusInWindow();
}
@Override
public void update(Observable o, Object arg) {
this.målarduk.repaint(); // called whenever Nivå.notifyObservers() fires
}
}public class Nivå extends Observable {
private ArrayList<Rum> rum;
private Rum nuvarandeRum;
public Nivå(Rum startrum, ArrayList<Rum> rum) {
if (startrum == null || rum == null)
throw new IllegalArgumentException("Start room and rooms cannot be null");
this.rum = rum;
this.nuvarandeRum = startrum;
if (!this.rum.contains(startrum))
throw new IllegalArgumentException("Start room is not included in the rooms");
// Validate no overlap
for (int i = 0; i < rum.size(); i++)
for (int j = i + 1; j < rum.size(); j++)
if (rum.get(i).getX() < rum.get(j).getX() + rum.get(j).getWall_width()
&& rum.get(i).getX() + rum.get(i).getWall_width() > rum.get(j).getX()
&& rum.get(i).getY() < rum.get(j).getY() + rum.get(j).getWall_height()
&& rum.get(i).getY() + rum.get(i).getWall_height() > rum.get(j).getY())
throw new IllegalArgumentException("Two rooms overlap");
}
public ArrayList<Rum> getRum() { return rum; }
public Rum getNuvarandeRum() { return nuvarandeRum; }
public void hoppaÅt(Väderstreck v) {
if (nuvarandeRum.finnsUtgångÅt(v)) {
nuvarandeRum = nuvarandeRum.gångenÅt(v).getTill();
setChanged();
notifyObservers(); // triggers GUI.update() → repaint
}
}
}public class Rum {
private int x, y, höjd, bredd;
private Color golvfärg;
private Gång[] gångar = new Gång[GlobalaKonstanter.ANTAL_VÄDERSTRECK];
public Rum(Color golvfärg, int bredd, int höjd, int övX, int övY) {
this.golvfärg = golvfärg;
this.höjd = höjd; this.bredd = bredd;
this.x = övX; this.y = övY;
}
public int getX() { return x; }
public int getY() { return y; }
public int getWall_height() { return höjd; }
public int getWall_width() { return bredd; }
public Color getFloor_color() { return golvfärg; }
public boolean finnsUtgångÅt(Väderstreck v) {
return gångar[v.index()] != null;
}
public Gång gångenÅt(Väderstreck v) {
if (gångar[v.index()] == null)
throw new IllegalArgumentException("No passage in that direction");
return gångar[v.index()];
}
public static void kopplaIhop(Rum från, Väderstreck ut, Rum till, Väderstreck in) {
if (från == null || till == null || ut == null || in == null)
throw new IllegalArgumentException("Params cannot be null");
if (från == till) throw new IllegalArgumentException("Same room");
if (från.finnsUtgångÅt(ut)) throw new IllegalArgumentException("Already connected (från)");
if (till.finnsUtgångÅt(in)) throw new IllegalArgumentException("Already connected (till)");
från.gångar[ut.index()] = new Gång(från, ut, till, in);
till.gångar[in.index()] = new Gång(till, in, från, ut);
}
}public class Gång {
private final Rum från;
private final Väderstreck riktningUtUrFrån;
private final Rum till;
private final Väderstreck riktningInITill;
public Gång(Rum från, Väderstreck riktningUtUrFrån,
Rum till, Väderstreck riktningInITill) {
this.från = från;
this.riktningUtUrFrån = riktningUtUrFrån;
this.till = till;
this.riktningInITill = riktningInITill;
}
public Rum getFrån() { return från; }
public Väderstreck getRiktningUtUrFrån() { return riktningUtUrFrån; }
public Rum getTill() { return till; }
public Väderstreck getRiktningInITill() { return riktningInITill; }
}public class Målarduk extends JPanel {
private final Nivå enNivå;
public Målarduk(Nivå enNivå) {
this.enNivå = enNivå;
setBackground(MARKFÄRG); // green background (Color.GREEN)
setFocusable(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rum r : enNivå.getRum()) ritaRum(g, r);
for (Rum r : enNivå.getRum()) ritaGångarFrånRum(g, r);
ritaMarkörFörVarAnvändarenÄr(g);
}
private void ritaRum(Graphics g, Rum r) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(r.getFloor_color());
g2.fillRect(r.getX(), r.getY(), r.getWall_width(), r.getWall_height());
g2.setColor(VÄGGFÄRG); // black
g2.setStroke(new BasicStroke(VÄGGTJOCKLEK)); // 8px walls
g2.drawRect(r.getX(), r.getY(), r.getWall_width(), r.getWall_height());
}
private void ritaGångarFrånRum(Graphics g, Rum r) {
for (Väderstreck v : Väderstreck.values())
if (r.finnsUtgångÅt(v)) {
Gång gång = r.gångenÅt(v);
if (gång.getFrån() == r) ritaGång(g, gång); // draw each once
}
}
private Punkt baspunkt(Rum r, Väderstreck v) {
int midX = r.getX() + r.getWall_width() / 2;
int midY = r.getY() + r.getWall_height() / 2;
switch (v) {
case NORR: return new Punkt(midX, r.getY());
case SÖDER: return new Punkt(midX, r.getY() + r.getWall_height());
case ÖSTER: return new Punkt(r.getX() + r.getWall_width(), midY);
case VÄSTER: return new Punkt(r.getX(), midY);
default: throw new IllegalArgumentException();
}
}
private Punkt pivotpunkt(Rum r, Väderstreck v) {
Punkt b = baspunkt(r, v); int o = 7;
switch (v) {
case NORR: return new Punkt(b.x(), b.y() - o);
case SÖDER: return new Punkt(b.x(), b.y() + o);
case ÖSTER: return new Punkt(b.x() + o, b.y());
case VÄSTER: return new Punkt(b.x() - o, b.y());
default: throw new IllegalArgumentException();
}
}
private void ritaGång(Graphics g, Gång gång) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(GÅNGFÄRG); // brown
g2.setStroke(new BasicStroke(VÄGGTJOCKLEK, CAP_ROUND, JOIN_ROUND));
Punkt bf = baspunkt(gång.getFrån(), gång.getRiktningUtUrFrån());
Punkt pf = pivotpunkt(gång.getFrån(), gång.getRiktningUtUrFrån());
Punkt pt = pivotpunkt(gång.getTill(), gång.getRiktningInITill());
Punkt bt = baspunkt(gång.getTill(), gång.getRiktningInITill());
g2.drawLine(bf.x(), bf.y(), pf.x(), pf.y());
g2.drawLine(pf.x(), pf.y(), pt.x(), pt.y());
g2.drawLine(pt.x(), pt.y(), bt.x(), bt.y());
}
private void ritaMarkörFörVarAnvändarenÄr(Graphics g) {
Rum r = enNivå.getNuvarandeRum();
int cx = r.getX() + r.getWall_width() / 2;
int cy = r.getY() + r.getWall_height() / 2;
g.setColor(ANVÄNDARFÄRG); // black
g.fillOval(cx - ANVÄNDARRADIE, cy - ANVÄNDARRADIE,
ANVÄNDARRADIE * 2, ANVÄNDARRADIE * 2);
}
}public class Tangentbordslyssnare implements KeyListener {
private Nivå enNivå;
public Tangentbordslyssnare(Nivå enNivå) { this.enNivå = enNivå; }
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) enNivå.hoppaÅt(Väderstreck.NORR);
else if (key == KeyEvent.VK_D) enNivå.hoppaÅt(Väderstreck.ÖSTER);
else if (key == KeyEvent.VK_S) enNivå.hoppaÅt(Väderstreck.SÖDER);
else if (key == KeyEvent.VK_A) enNivå.hoppaÅt(Väderstreck.VÄSTER);
}
@Override public void keyTyped(KeyEvent e) {} // required by interface
@Override public void keyReleased(KeyEvent e) {} // required by interface
}public class Huvudprogram {
public static void main(String[] args) {
ArrayList<Rum> rum = new ArrayList<Rum>();
// new Rum(color, bredd, höjd, x, y)
rum.add(new Rum(Color.RED, 75, 75, 25, 25)); // 0
rum.add(new Rum(Color.BLUE, 75, 50, 50, 150)); // 1
rum.add(new Rum(Color.MAGENTA,100, 50, 175, 100)); // 2
rum.add(new Rum(Color.YELLOW, 100, 75, 200, 200)); // 3
rum.add(new Rum(Color.CYAN, 100, 75, 325, 50)); // 4
rum.add(new Rum(Color.ORANGE, 75, 75, 450, 125)); // 5 ← start
rum.add(new Rum(Color.PINK, 100, 50, 275, 325)); // 6
rum.add(new Rum(Color.GREEN, 75, 100, 75, 275)); // 7
Rum.kopplaIhop(rum.get(0), SÖDER, rum.get(1), NORR);
Rum.kopplaIhop(rum.get(0), ÖSTER, rum.get(2), NORR);
Rum.kopplaIhop(rum.get(1), SÖDER, rum.get(3), VÄSTER);
Rum.kopplaIhop(rum.get(2), SÖDER, rum.get(3), NORR);
Rum.kopplaIhop(rum.get(2), ÖSTER, rum.get(4), VÄSTER);
Rum.kopplaIhop(rum.get(4), ÖSTER, rum.get(5), NORR);
Rum.kopplaIhop(rum.get(5), SÖDER, rum.get(6), ÖSTER);
Rum.kopplaIhop(rum.get(3), ÖSTER, rum.get(5), VÄSTER);
Rum.kopplaIhop(rum.get(3), SÖDER, rum.get(6), NORR);
Rum.kopplaIhop(rum.get(7), ÖSTER, rum.get(6), VÄSTER);
Nivå nivå = new Nivå(rum.get(5), rum); // start at Orange (index 5)
new GUI(nivå);
}
}package labb3.verktyg;
// Static utility methods for drawing on a Graphics context
public class Grafik {
// Draw a thick line between two points
public static void drawThickLine(Graphics g, Punkt start, Punkt slut,
int width, Color c) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(c);
g2d.setStroke(new BasicStroke((float) width,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2d.drawLine(start.x(), start.y(), slut.x(), slut.y());
g2d.setStroke(new BasicStroke(1));
}
// Draw a filled circle centered at a point with given radius
public static void fillCircle(Graphics g, Punkt mittpunkt,
int radie, Color c) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(c);
g2d.setStroke(new BasicStroke(1));
g2d.fillOval(mittpunkt.x() - radie, mittpunkt.y() - radie,
2 * radie, 2 * radie);
}
}package labb3.verktyg;
// Immutable point, used for corridor base/pivot calculations
public class Punkt {
private final int x, y;
public Punkt(int x, int y) { this.x = x; this.y = y; }
public int x() { return x; }
public int y() { return y; }
public String toString() { return "(" + x() + "," + y() + ")"; }
}
// Immutable so it can safely be shared between methods without defensive copiespackage labb3;
// Shared constants used across all drawing classes
abstract public class GlobalaKonstanter {
// Wall appearance
public static final int VÄGGTJOCKLEK = 8;
public static final int HALV_VÄGGTJOCKLEK = VÄGGTJOCKLEK / 2;
public static final int DUBBEL_VÄGGTJOCKLEK= VÄGGTJOCKLEK * 2;
public static final Color VÄGGFÄRG = Color.BLACK;
// Corridor appearance
public static final Color GÅNGFÄRG = new Color(123, 63, 0); // brown
// Background (the "ground" between rooms)
public static final Color MARKFÄRG = Color.GREEN;
// Player marker
public static final Color ANVÄNDARFÄRG = Color.BLACK;
public static final int ANVÄNDARRADIE = HALV_VÄGGTJOCKLEK; // = 4
// Direction count (N, E, S, W)
public static final int ANTAL_VÄDERSTRECK = 4;
}Two data structures working together
FIFO.java implements a circular-buffer queue.
GraphIO.java reads a graph from a file.
The BFS algorithm uses the FIFO queue to visit every node
in the graph level by level, nearest nodes first.
Click any node below to watch BFS spread outward, and see the queue state at each step.
Click any node to start BFS from there. Watch it sweep outward level by level. The FIFO queue state is shown live, each level gets a new colour. Switch between the two graph files from class.
Click any dot on the graph to start, or just hit Step or Run to pick a random start automatically.
public class FIFO implements Queue {
private Object[] data;
private int size, front, back;
public FIFO(int capacity) {
data = new Object[capacity];
size = 0; front = 0; back = 0;
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public int maxSize() { return data.length; }
public Object first() {
if (isEmpty()) throw new NoSuchElementException("Queue is empty");
return data[front];
}
// Circular buffer: wrap index with modulo instead of shifting elements
public void removeFirst() {
if (isEmpty()) throw new NoSuchElementException("Queue is empty");
data[front] = null;
front = (front + 1) % data.length; // wrap around
size--;
}
public void add(Object o) {
if (size == data.length) throw new IllegalStateException("Queue is full");
data[back] = o;
back = (back + 1) % data.length; // wrap around
size++;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof FIFO)) return false;
FIFO other = (FIFO) obj;
if (this.size != other.size) return false;
for (int i = 0; i < size; i++) {
Object a = this.data[(front + i) % data.length];
Object b = other.data[(other.front + i) % other.data.length];
if (a == null ? b != null : !a.equals(b)) return false;
}
return true;
}
}public class GraphIO {
public static void readFile(Graph graph, String filename) {
try (Scanner sc = new Scanner(new File(filename))) {
int n = sc.nextInt(); // number of nodes
for (int i = 0; i < n; i++) {
int id = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
graph.addNode(id, x, y);
}
// edges: from → to with weight
while (sc.hasNextInt()) {
int from = sc.nextInt();
int to = sc.nextInt();
int w = sc.nextInt();
graph.addEdge(from, to, w);
}
} catch (NoSuchElementException e) {
throw new IllegalArgumentException("Bad file format: " + filename);
}
}
}
// gridgraph file format:
// Line 1: 100 (number of nodes)
// Lines 2-101: id x y (node id and coordinates)
// Rest: from to w (edges with weight)// Breadth-First Traversal using our FIFO queue
void bft(Graph graph, int startId) {
FIFO queue = new FIFO(graph.nodeCount());
boolean[] visited = new boolean[graph.nodeCount()];
queue.add(startId);
visited[startId] = true;
while (!queue.isEmpty()) {
int current = (int) queue.first();
queue.removeFirst(); // dequeue front (FIFO order)
System.out.println("Visiting node " + current);
// enqueue all unvisited neighbours
for (int neighbour : graph.neighbours(current)) {
if (!visited[neighbour]) {
visited[neighbour] = true;
queue.add(neighbour); // visit nearest nodes first
}
}
}
}
// Key insight: FIFO order guarantees BFS visits nodes
// level by level, all distance-1 nodes before distance-2, etc.
// A Stack (LIFO) here would give DFS instead.A state machine disguised as a calculator
The calculator is built around four states: Input1 → OpReady → Input2 → HasResult.
Each button type is its own class extending the abstract CalculatorButton, and each implements a transition() method that changes the state.
The Situation object holds all shared state: display, operands, current operator.
Fully functional calculator, exact port of the Java Swing version. The current state is shown live so you can see the state machine in action as you type.
// The 4 states of the calculator state machine
public enum State {
Input1, // entering first number
OpReady, // operator selected, waiting for second number
Input2, // entering second number
HasResult // result shown, ready for next calc
}// Holds all shared mutable state, passed to every button
public class Situation {
public State state;
public int leftOperand;
public JLabel display;
public BinOpButton binaryOperator;
public Situation(JLabel display) {
this.display = display;
this.state = State.Input1;
this.leftOperand = 0;
this.binaryOperator = null;
this.display.setText("0");
}
}// Abstract base, all buttons share a Situation reference
// and fire transition() when clicked
public abstract class CalculatorButton extends JButton {
protected final Situation situation;
public CalculatorButton(String text, Situation situation) {
super(text);
this.situation = situation;
addActionListener(e -> transition()); // wires click to state change
}
protected abstract void transition(); // each subclass defines its own
}public class DigitButton extends CalculatorButton {
private final int digit;
@Override
protected void transition() {
String current = situation.display.getText();
switch (situation.state) {
case Input1:
// append digit (replace if showing 0)
if (current.equals("0")) situation.display.setText("" + digit);
else situation.display.setText(current + digit);
break;
case OpReady:
// first digit of second number, switch state
situation.display.setText("" + digit);
situation.state = State.Input2;
break;
case Input2:
if (current.equals("0")) situation.display.setText("" + digit);
else situation.display.setText(current + digit);
break;
case HasResult:
// start fresh after seeing result
situation.leftOperand = 0;
situation.binaryOperator = null;
situation.display.setText("" + digit);
situation.state = State.Input1;
break;
}
}
}public class BinOpButton extends CalculatorButton {
private final char op;
public int apply(int a, int b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b; // integer division
default: throw new IllegalStateException("Unknown operator: " + op);
}
}
@Override
protected void transition() {
try {
int current = Integer.parseInt(situation.display.getText());
switch (situation.state) {
case Input1:
case HasResult:
// save left operand, set operator, wait for second number
situation.leftOperand = current;
situation.binaryOperator = this;
situation.state = State.OpReady;
break;
case OpReady:
// just changing mind about operator
situation.binaryOperator = this;
break;
case Input2:
// chain operation: compute first, then set new op
int result = situation.binaryOperator.apply(situation.leftOperand, current);
situation.display.setText("" + result);
situation.leftOperand = result;
situation.binaryOperator = this;
situation.state = State.OpReady;
break;
}
} catch (ArithmeticException ex) {
situation.display.setText("0");
situation.leftOperand = 0;
situation.binaryOperator = null;
situation.state = State.Input1;
}
}
}public class EqualsButton extends CalculatorButton {
@Override
protected void transition() {
try {
int current = Integer.parseInt(situation.display.getText());
switch (situation.state) {
case Input2:
// only state where = does something
int result = situation.binaryOperator.apply(situation.leftOperand, current);
situation.display.setText("" + result);
situation.leftOperand = result;
situation.state = State.HasResult;
break;
case Input1:
case OpReady:
case HasResult:
break; // do nothing
}
} catch (Exception ex) {
situation.display.setText("0");
situation.state = State.Input1;
}
}
}public class GUI extends JFrame {
public GUI(Situation situation) {
setLayout(new BorderLayout());
// Display, right-aligned, large font
situation.display.setHorizontalAlignment(SwingConstants.RIGHT);
situation.display.setFont(new Font("Arial", Font.BOLD, 24));
add(situation.display, BorderLayout.NORTH);
// 4×4 button grid
JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
panel.add(new DigitButton(7, situation));
panel.add(new DigitButton(8, situation));
panel.add(new DigitButton(9, situation));
panel.add(new BinOpButton('/', situation));
panel.add(new DigitButton(4, situation));
panel.add(new DigitButton(5, situation));
panel.add(new DigitButton(6, situation));
panel.add(new BinOpButton('*', situation));
panel.add(new DigitButton(1, situation));
panel.add(new DigitButton(2, situation));
panel.add(new DigitButton(3, situation));
panel.add(new BinOpButton('-', situation));
panel.add(new DigitButton(0, situation));
panel.add(new EqualsButton(situation));
panel.add(new CancelButton(situation));
panel.add(new BinOpButton('+', situation));
add(panel, BorderLayout.CENTER);
setSize(300, 400);
setVisible(true);
}
}A full simulation engine from scratch
A car wash with fast and slow machines. Cars arrive randomly (exponential distribution),
wait in a bounded queue, and depart after being washed (uniform distribution).
Built on a reusable simulation framework: Simulator drives an
EventQueue (priority queue), each Event
modifies the State and may schedule new events.
The random package was provided by the course.
Run the exact simulation from Main.java, 2 fast machines, 2 slow machines, queue of 5, λ=2, seed=1234.
Step through each event or run the full simulation and see the event log, machine states, and queue live.
Adjust the parameters and re-run for different results.
UML class diagram showing the architecture: inheritance, composition, and dependencies between the three packages.
Lab 6: Design notes
This document describes the initial design plan for the simulation. The UML diagram represents the intended architecture before implementation.
Package structure
Generates random numbers. Provided by course instructors. ExponentialRandomStream for inter-arrival times. UniformRandomStream for service times.
Generic reusable simulation engine, not specific to car wash. Simulator drives the event loop. EventQueue uses a PriorityQueue ordered by time. Event is abstract with compareTo() for ordering. State holds time and stop flag.
Car-wash-specific logic. CarWashState extends State. Each event type (Arrival, Departure, Close, Stop) extends Event and implements execute(). EventFactory centralises event creation to reduce coupling.
Key design decisions
- EventFactory centralises event creation instead of letting events create each other directly. This reduces coupling and keeps responsibilities clear.
- Event implements Comparable<Event> so the PriorityQueue orders events by time automatically.
- CarWashState extends State. The generic framework knows nothing about car washing, only the carwash package does.
- SimulationView separates display from logic, state delegates printing to the view.
// Abstract base, all events share a time and an execute() method
public abstract class Event implements Comparable<Event> {
private final double time;
protected Event(double time) { this.time = time; }
protected double getTime() { return time; }
// Each subclass defines what happens when the event fires
public abstract void execute(State state, EventQueue queue);
// Natural ordering by time, used by PriorityQueue in EventQueue
@Override
public int compareTo(Event other) {
return Double.compare(this.time, other.time);
}
}public class Simulator {
private final EventQueue eventQueue;
private final State state;
public void run() {
// Core simulation loop, process events in time order
while (!state.isStopped() && !eventQueue.isEmpty()) {
Event e = eventQueue.next(); // always the earliest event
state.setTime(e.getTime()); // advance simulation clock
e.execute(state, eventQueue); // fire the event
}
}
}
// EventQueue uses PriorityQueue<Event>, Event.compareTo() ensures
// the minimum-time event is always returned by next()class ArrivalEvent extends Event {
private final EventFactory factory;
@Override
public void execute(State s, EventQueue q) {
CarWashState state = (CarWashState) s;
state.updateTimes(getTime()); // accumulate idle + queue times
if (state.isClosed()) return; // car wash closed, ignore arrival
state.incArrived();
Car car = factory.newCar(getTime());
// Priority: fast machine first, then slow, then queue, then reject
if (state.getFreeFast() > 0) {
state.takeFast();
factory.scheduleDeparture(getTime(), car, true);
} else if (state.getFreeSlow() > 0) {
state.takeSlow();
factory.scheduleDeparture(getTime(), car, false);
} else if (state.getQueue().size() < state.getMaxQueue()) {
state.getQueue().add(car); // join the queue
} else {
state.incRejected(); // queue full → turned away
}
state.printRow(getTime(), "Arrive", String.valueOf(car.getId()));
factory.scheduleNextArrival(getTime()); // schedule next car
}
}class DepartureEvent extends Event {
private final Car car;
private final boolean fast; // which machine type was used
private final EventFactory factory;
@Override
public void execute(State s, EventQueue q) {
CarWashState state = (CarWashState) s;
state.updateTimes(getTime());
state.incServed();
state.printRow(getTime(), "Leave", String.valueOf(car.getId()));
// Free the machine that was used
if (fast) state.releaseFast();
else state.releaseSlow();
// Immediately serve the next waiting car (if any)
if (!state.getQueue().isEmpty()) {
Car next = state.getQueue().poll();
if (fast) state.takeFast();
else state.takeSlow();
factory.scheduleDeparture(getTime(), next, fast);
}
}
}class CarWashState extends State {
private int freeFast, freeSlow;
private final Queue<Car> queue = new ArrayDeque<>();
private double totalIdleTime, totalQueueTime, lastEventTime;
// Called at the start of every event to accumulate statistics
void updateTimes(double now) {
double dt = now - lastEventTime;
// Every idle machine accumulates idle time
totalIdleTime += dt * (getFreeFast() + getFreeSlow());
// Every waiting car accumulates queue time
totalQueueTime += dt * queue.size();
lastEventTime = now;
}
// Final statistics output
void printSummary() {
int entered = totalArrived - totalRejected;
double meanQ = (entered == 0) ? 0.0 : (totalQueueTime / entered);
view.printSummary(totalIdleTime, totalQueueTime, meanQ, totalRejected);
}
}package carwash;
import simulation.Event;
import simulation.EventQueue;
import simulation.State;
/**
* Represents the event when the car wash stops accepting new arrivals.
* This event marks the closing time - no new cars will be accepted after this.
*/
class CloseEvent extends Event {
/**
* Creates a close event at a specific time.
*
* @param time The time when the car wash should stop accepting arrivals
*/
CloseEvent(double time) {
super(time);
}
/**
* Executes the close event by marking the car wash as closed.
* After this, no new cars will be accepted into the system.
*
* @param s The current state of the car wash
* @param q The event queue
*/
@Override
public void execute(State s, EventQueue q) {
CarWashState state = (CarWashState) s;
state.updateTimes(getTime());
// Mark the car wash as closed to new arrivals
state.closeArrivals();
}
}package carwash;
import simulation.Event;
import simulation.EventQueue;
import simulation.State;
/**
* Represents the event that stops the entire simulation.
* This is the final event that terminates the simulation and prints the
* summary.
*/
class StopEvent extends Event {
/**
* Creates a stop event at a specific time.
*
* @param time The time when the simulation should stop
*/
StopEvent(double time) {
super(time);
}
/**
* Executes the stop event by ending the simulation and printing the final
* summary.
*
* @param state The current state of the car wash
* @param queue The event queue
*/
@Override
public void execute(State state, EventQueue queue) {
CarWashState s = (CarWashState) state;
s.updateTimes(getTime());
s.printRow(getTime(), "Stop", "");
state.stop();
s.printSummary();
}
}package carwash;
import random.ExponentialRandomStream;
import random.UniformRandomStream;
import simulation.EventQueue;
/**
* Factory class responsible for creating and scheduling all events in the
* simulation.
* Handles arrivals, departures, closing, and stopping the simulation.
*/
class EventFactory {
// Random stream for car arrival times (exponential distribution)
private final ExponentialRandomStream arrivalStream;
// Random stream for fast machine wash times (uniform distribution)
private final UniformRandomStream fastWashStream;
// Random stream for slow machine wash times (uniform distribution)
private final UniformRandomStream slowWashStream;
// The event queue where all events are stored
private EventQueue queue;
// Counter for assigning unique IDs to cars
private int nextCarId = 0;
// The time when the car wash stops accepting new arrivals
private final double closeTime;
// The time when the entire simulation stops
private final double stopTime;
/**
* Creates a new event factory with the specified random streams and time
* settings.
*
* @param arrivalStream Random stream for car arrivals
* @param fastWashStream Random stream for fast machine wash times
* @param slowWashStream Random stream for slow machine wash times
* @param closeTime Time when the car wash stops accepting arrivals
* @param stopTime Time when the simulation stops
*/
EventFactory(
ExponentialRandomStream arrivalStream,
UniformRandomStream fastWashStream,
UniformRandomStream slowWashStream,
double closeTime,
double stopTime) {
this.arrivalStream = arrivalStream;
this.fastWashStream = fastWashStream;
this.slowWashStream = slowWashStream;
this.closeTime = closeTime;
this.stopTime = stopTime;
}
/**
* Initializes the factory with the event queue and state.
* Schedules the initial events: first arrival, closing event, and stop event.
*
* @param queue The event queue
* @param state The car wash state
*/
void init(EventQueue queue, CarWashState state) {
this.queue = queue;
// Schedule the first arrival
scheduleNextArrival(0.0);
// Schedule when the car wash closes to new arrivals
queue.add(new CloseEvent(closeTime));
// Schedule when the simulation stops
queue.add(new StopEvent(stopTime));
}
/**
* Schedules the next car arrival.
* The time is determined by the arrival random stream.
*
* @param currentTime The current simulation time
*/
void scheduleNextArrival(double currentTime) {
// Generate the time until the next arrival
double dt = arrivalStream.next();
double nextTime = currentTime + dt;
// Only schedule if it happens before closing time
if (nextTime < closeTime)
queue.add(new ArrivalEvent(nextTime, this));
}
/**
* Schedules a departure event for a car after it finishes washing.
*
* @param currentTime The current simulation time
* @param car The car to wash
* @param fast True for fast machine, false for slow
* @return The wash time that was generated
*/
void scheduleDeparture(double currentTime, Car car, boolean fast) {
// Generate a random wash time based on the machine type
double washTime = fast ? fastWashStream.next() : slowWashStream.next();
// Schedule the departure event
queue.add(new DepartureEvent(currentTime + washTime, car, fast, this));
}
/**
* Creates a new car with a unique ID.
*
* @param arrivalTime The time this car arrived
* @return A new Car object
*/
Car newCar(double arrivalTime) {
return new Car(nextCarId++, arrivalTime);
}
}package carwash;
/**
* Represents a car that arrives at the car wash.
* Stores the car's unique ID and the time it arrived.
*/
class Car {
// Unique identifier for this car
private final int id;
// The time when this car arrived at the car wash
private final double arrivalTime;
/**
* Creates a new car with a unique ID and arrival time.
*
* @param id Unique identifier for this car
* @param arrivalTime The time this car arrived
*/
Car(int id, double arrivalTime) {
this.id = id;
this.arrivalTime = arrivalTime;
}
/**
* Gets the car's unique ID.
*
* @return The car's ID
*/
int getId() {
return id;
}
/**
* Gets the time this car arrived.
*
* @return The arrival time
*/
double getArrivalTime() {
return arrivalTime;
}
}package simulation;
/**
* Base class for simulation state.
* Tracks the current simulation time and whether the simulation is running.
*/
public class State {
// Current simulation time
private double time;
// Flag indicating if the simulation should stop
private boolean stopFlag;
/**
* Gets the current simulation time.
*
* @return The current time
*/
protected double getTime() {
return time;
}
/**
* Sets the current simulation time.
*
* @param t The new time
*/
protected void setTime(double t) {
this.time = t;
}
/**
* Signals the simulation to stop.
*/
public void stop() {
this.stopFlag = true;
}
/**
* Checks if the simulation has been stopped.
*
* @return true if simulation is stopped, false otherwise
*/
protected boolean isStopped() {
return stopFlag;
}
}package simulation;
import java.util.PriorityQueue;
/**
* A queue that stores events in chronological order.
* Events are always retrieved in order of their occurrence time.
*/
public class EventQueue {
// Priority queue that orders events by time
private final PriorityQueue<Event> pq = new PriorityQueue<>();
/**
* Adds an event to the queue.
* The event will be stored in chronological order.
*
* @param e The event to add
*/
public void add(Event e) {
pq.add(e);
}
/**
* Gets and removes the next event from the queue.
*
* @return The event that occurs next in time
*/
protected Event next() {
return pq.poll();
}
/**
* Checks if the queue is empty.
*
* @return true if no events are scheduled, false otherwise
*/
protected boolean isEmpty() {
return pq.isEmpty();
}
}package carwash;
import random.ExponentialRandomStream;
import random.UniformRandomStream;
import simulation.EventQueue;
import simulation.Simulator;
/**
* Main entry point for the car wash simulation.
* This program simulates a car wash facility with two types of machines (fast
* and slow).
* Cars arrive randomly, wait in a queue if necessary, and leave after being
* washed.
*
* To run and compile:
* javac carwash/*.java simulation/*.java random/*.java
* java carwash.Main
*/
public class Main {
/**
* Runs the car wash simulation with predefined parameters.
*/
public static void main(String[] args) {
// Configuration: number of washing machines
int fastStations = 2; // Number of fast machines
int slowStations = 2; // Number of slow machines
int maxQueue = 5; // Maximum queue size
// Configuration: simulation timing
double closeTime = 15.0; // When to stop accepting new arrivals
double stopTime = 15.0; // When to end the simulation
// Configuration: random distributions
double lambda = 2.0; // Rate parameter for exponential arrivals
int seed = 1234; // Seed for random number generation
// Configuration: wash time ranges (minutes)
double fastMin = 2.8, fastMax = 4.6; // Fast machine wash time range
double slowMin = 3.5, slowMax = 6.7; // Slow machine wash time range
// Create random streams for generating random numbers
ExponentialRandomStream arrival = new ExponentialRandomStream(lambda, seed);
UniformRandomStream fastWash = new UniformRandomStream(fastMin, fastMax, seed);
UniformRandomStream slowWash = new UniformRandomStream(slowMin, slowMax, seed);
// Create the simulation components
EventQueue q = new EventQueue(); // Event queue
CarWashState state = new CarWashState(fastStations, slowStations, maxQueue); // State
// Create the simulation view and link it to the state
SimulationView view = new SimulationView();
state.setView(view); // Set the view in the state for updates
// Create factory and initialize with first events
EventFactory factory = new EventFactory(arrival, fastWash, slowWash, closeTime, stopTime);
factory.init(q, state);
// Print configuration information
System.out.println("Fast machines: " + fastStations);
System.out.println("Slow machines: " + slowStations);
System.out.println("Fast distribution: (" + fastMin + ", " + fastMax + ")");
System.out.println("Slow distribution: (" + slowMin + ", " + slowMax + ")");
System.out.println("Exponential distribution with lambda = " + lambda);
System.out.println("seed = " + seed);
System.out.println("Max Queue size: " + maxQueue);
// Print the header and start row
view.printHeader();
view.printRow(0.0, "Start", "",
state.getFreeFast(),
state.getFreeSlow(),
state.getTotalIdleTime(),
state.getTotalQueueTime(),
state.getQueue().size(),
state.getTotalRejected());
// Run the simulation
Simulator sim = new Simulator(q, state);
sim.run();
}
}What I learned
It is an ordinary array that gets copied to a bigger one when it fills up. Writing it made it clear why adding at the end is cheap on average and removing from the middle is not.
In the room game the level only says that something changed. The window listens and redraws itself, so the rules never mention graphics.
The car wash simulation does not count seconds. It takes the next event from a queue sorted by time and moves the clock straight to it.
The FIFO queue wraps around with modulo, so nothing has to be shifted when the first element leaves.