THINK FIRST·CODE LATER

← Java Programming

Programming labs

Write the program yourself, then compare with the model solution. The problems follow the chapters, from the first programs to object-oriented design.

CPS 2231 · 72 labs

Chapter 10 Classes, Objects, and Encapsulation 9 labs

L10.1 Easy

Rectangle: a first class with accessors

Write a class Rectangle with two private instance variables width and height (double), a constructor taking both, accessors getWidth() and getHeight()...

L10.2 Easy

Thermostat: an object that protects its state

Write a class Thermostat (not public, in the same file) and a public class ThermostatApp. Thermostat has private fields target (starts at 20) and on (...

L10.3 Medium

Fraction: an immutable value class

Write a class Fraction and a public class FractionApp. A Fraction has two private final ints, num and den, and is always stored in lowest terms with a...

L10.4 Medium

Time: hide how the data is stored

Write a class Time and a public class TimeOfDay. Time stores the time of day in one private field: the number of seconds since midnight (0 … 86 399)....

L10.5 Medium

A PIN lock that blocks after three mistakes

Write a class PinLock and a public class PinLockApp. A lock has a private PIN, a count of failed attempts and an open/closed state. No method ever ret...

L10.6 Easy

Stock: a class that computes from its own data

Write a class Stock (not public, same file) and a public class StockApp. A Stock has four private fields: symbol, name, previousClosingPrice and curre...

L10.7 Medium

Fan: constants and guarded mutators

Write a class Fan and a public class FanApp. Fan has three public constants SLOW = 1, MEDIUM = 2, FAST = 3 and four private fields with these starting...

L10.8 Medium

QuadraticEquation: an object that answers questions

Write a class QuadraticEquation for ax² + bx + c = 0 and a public class QuadraticApp. The class has three private fields a, b, c set by the constructo...

A5 Medium

Student and StudentApp: class design

Design a Student class with attributes id, name, age and grade; a default and a parameterised constructor; getters and setters for all attributes; dis...

Chapter 11 Object References, Constructors, and Overloading 9 labs

L11.1 Medium

Book: overloaded constructors and equality

Write a class Book with private fields title (String), author (String) and year (int), and: - a constructor with the three values; - a second construc...

L11.2 Easy

Aliases and copy constructors

Write a class Point with private x and y, a normal constructor, a copy constructor Point(Point other) (it should call the first constructor with this(...

L11.3 Medium

Money: overloaded constructors and methods

Money must never be stored in a double (0.1 + 0.2 ≠ 0.3). Write a class Money that stores whole fen in a private final long (1 yuan = 100 fen), with t...

L11.4 Medium

What methods can and cannot change

Write a class Wallet (owner, private balance, deposit, withdraw, toString → Lina: 120) and a public class TransferDemo with three static methods: - bo...

L11.5 Medium

SimpleDate: three constructors and methods that return objects

Write an immutable class SimpleDate (private final year, month, day) and a public class DateApp. - Three overloaded constructors: SimpleDate(int, int,...

L11.6 Medium

MyPoint: overloaded constructors and methods

Write a class MyPoint and a public class PointApp. - Two constructors: MyPoint() creates the origin by calling the other one with this(0, 0); MyPoint(...

L11.7 Medium

Circle2D: objects as arguments

Write a class Circle2D (centre x, y and radius, all private) and a public class CircleApp. - Circle2D() creates the circle of radius 1 centred at the...

L11.8 Hard

IntQueue: an object that manages its own array

A queue serves its elements in their order of arrival. Write a class IntQueue and a public class IntQueueApp. IntQueue hides an int[] elements and a c...

A6 Medium

MyClass: completing an instance method

Complete the program so that it prints 1 and then 2.

Chapter 12 Class Members, Utility Classes, and Program Design 9 labs

L12.1 Medium

Utility class and object counter

Write a class Temperature with: - a private field celsius; - a static counter of how many Temperature objects were created, readable with public stati...

L12.2 Easy

Library cards: static vs instance members

Write a class Member with: - static fields nextNumber (starts at 1) and activeCount, and a constant PREFIX = "LIB"; - instance fields id, name, active...

L12.3 Medium

A utility class: MathTools

Write a utility class MathTools: declared final, with a private constructor (nobody can create an object), and only static methods: - boolean isPrime(...

L12.4 Medium

Parking fees: top-down design

Design the program top-down: first write main in terms of methods that do not exist yet, then implement each method. A campus car park charges: the fi...

L12.5 Medium

StringTools: design and test a utility class

Write a utility class StringTools (final, private constructor, a constant VOWELS, static methods only): - countVowels(s); - countWords(s) — words are...

L12.6 Medium

MyInteger: the same question, asked two ways

Write a class MyInteger that wraps one int value, and a public class MyIntegerApp. The lab is about the difference between instance and static methods...

L12.7 Easy

CharTools: write your own Character utility class

Java's Character class is a utility class: only static methods, and no objects. Write your own, CharTools, without calling Character: isDigit, isUpper...

L12.8 Hard

A split that keeps the delimiters

"3+452".split(...) loses the operators. Write a utility class Splitter with a static method [code] that cuts the text at every character found in deli...

A10 Medium

BankAccount: encapsulation and a class counter

Write a BankAccount class with a private balance, a static counter of accounts created, an automatically assigned account number, deposit, withdraw th...

Chapter 13 ArrayList, StringBuilder, and Arrays of Objects 9 labs

L13.1 Medium

ArrayList of students

Write a class Student with private fields name and grade (int), a constructor, getName(), getGrade() and toString() returning name (grade). StudentLis...

L13.2 Easy

StringBuilder: reverse and palindrome

Write a class Palindrome with a method [code] that returns true when the text reads the same in both directions, ignoring case, spaces and punctuation...

L13.3 Medium

Shopping cart with an ArrayList

Write a class CartItem (name, price, quantity, addQuantity, subtotal, toString formatted %-10s %2d x %6.2f = %7.2f) and a public class ShoppingCart th...

L13.4 Medium

Run-length compression with StringBuilder

Run-length encoding replaces repeated characters by one character and a count: aaabccdddd → a3bc2d4 (a count of 1 is not written). Write RunLength wit...

L13.5 Medium

Product catalog: an array of objects

Write a class Product (name, category, price, stock; toString formatted %-10s %-8s %8.2f stock %d) and a public class ProductCatalog. main reads n, th...

L13.6 Medium

Playlist manager

Write a class Song (title, seconds, toString → Intro (1:05)) and a public class Playlist that keeps an ArrayList<Song. Commands until the end of input...

L13.7 Medium

An ArrayList toolbox

Write ListToolsApp with five static methods on ArrayList<Integer: - readList(Scanner in) — reads a count, then that many numbers; - max(list) — the la...

L13.8 Hard

MyBuilder: how a StringBuilder works inside

A String cannot be changed; a StringBuilder can, because it keeps its characters in an array with spare room. Write your own small version, MyBuilder,...

L13.9 Medium

The smallest multiplier that makes a perfect square

For a whole number m, find the smallest whole number n such that m × n is a perfect square. Example: 1500 = 2 × 2 × 3 × 5 × 5 × 5; the factors 3 and 5...

Chapter 14 Inheritance, Composition, and Aggregation 9 labs

L14.1 Medium

Employee and Manager: inheritance

Write a class Employee with private name and salary (double), a constructor, getName(), getSalary(), a method raise(double percent) that increases the...

L14.2 Medium

Highway tolls: overriding methods

Write a superclass Vehicle (protected plate and km, toll() = 0.5 yuan per km, type(), and toString() formatted %-6s %-9s %4d km toll %7.2f using type(...

L14.3 Medium

Composition and aggregation: course roster

Model courses and students: - Student (name, number of enrolled courses) — students exist independently of courses; - MeetingTime (day, start hour) —...

L14.4 Hard

Savings and checking accounts

Write a superclass Account (protected id and balance; deposit, boolean withdraw that refuses non-positive amounts or more than the balance, an empty m...

L14.5 Easy

People on campus: constructors and super

Write Person (private name and birth year, getName(), ageIn(int year), role() → Person, toString() → Person Mei (born 1990)), and two subclasses: - Ca...

L14.6 Medium

Arena: fighters that override behaviour

Write a superclass Fighter (protected name, health, power; attack(int round) returns power; takeDamage(int damage) never lets health go below 0; toStr...

L14.7 Easy

Triangle extends GeometricObject

Write a superclass GeometricObject (private color and filled, a constructor, the two accessors and toString() giving color red, filled), a subclass Tr...

L14.8 Medium

A stack two ways: is-a or has-a?

A stack only allows push, pop and peek at its top. Build it twice, on top of ArrayList<String: - InheritedStack extends ArrayList<String — adds push,...

L14.9 Medium

An account that keeps its history

Write the classes Transaction and Account, and a public class AccountHistory. - A Transaction records its number, its type ('D' deposit or 'W' withdra...

Chapter 15 Polymorphism, Abstract Classes, and Interfaces 9 labs

L15.1 Hard

Payable interface and polymorphism

Write an interface Payable with one method double pay(). Write two classes implementing it: - HourlyWorker(String name, double hours, double rate) — p...

L15.2 Medium

Payroll with an abstract class

Write an abstract class Employee (name, abstract double monthlyPay(), abstract String kind(), and a concrete toString() formatted %-10s %-10s %9.2f) a...

L15.3 Medium

Race results with Comparable

Write a class Runner implements Comparable<Runner (name, club, time in seconds — the constructor parses "42:07"). compareTo orders faster runners firs...

L15.4 Medium

Discounts through an interface

Write an interface Discountable with a constant MAX_RATE = 0.5, an abstract method double discountRate() and a default method double discountOn(double...

L15.5 Medium

One message, three channels: programming to an interface

Write an interface Notifier with String send(String message), int cost() (in fen) and String channel(), and three classes that implement it: - EmailNo...

L15.6 Easy

Which shapes can be colored? An interface as an ability

Write: - an interface Colorable with one method, String howToColor(); - an abstract class Shape with the abstract methods getArea() and getName(); - S...

L15.7 Medium

Complex numbers that can be compared

A complex number a + bi has a real part a and an imaginary part b. Write an immutable class Complex implements Comparable<Complex and a public class C...

L15.8 Medium

Floor plan: total area through an abstract class

An architect's plan lists rooms of different shapes. Write an abstract class Room with a name, the abstract method getArea(), a concrete method paintN...

A11 Medium

Shape hierarchy: abstract class, polymorphism and an interface

Write an abstract Shape with area() and perimeter(), subclasses Circle, Rectangle and IsoscelesRightTriangle, and an interface Scalable implemented by...

Chapter 16 Exception Handling 9 labs

L16.1 Medium

InsufficientFundsException

Write a checked exception InsufficientFundsException whose message is Missing 50.00, where the number is the amount that is lacking. Write a class Acc...

L16.2 Medium

A calculator that never crashes

Write SafeCalculator. Each input line is an expression a op b with integers and one of + - / %. A method int apply(int a, String op, int b) computes i...

L16.3 Hard

Config loader: a custom checked exception

A server reads its settings as key = value lines (empty lines and lines starting with are ignored). Valid keys are port, threads and timeout, with def...

L16.4 Easy

Indexes that cannot be trusted

SafeArray creates an array of 10 numbers in which values[i] is i × i + 1. It then reads words until the end of the input; each word is supposed to be...

L16.5 Medium

IllegalTriangleException: an object that refuses to be built

Three lengths form a triangle only if they are all positive and the sum of any two is greater than the third. Write: - a checked exception IllegalTria...

L16.6 Medium

Binary and hexadecimal: your own format exceptions

Write two unchecked exceptions, BinaryFormatException and HexFormatException, both extending NumberFormatException. Each receives the faulty text and...

A7 Medium

TimeFormatException: a custom checked exception

Write a checked exception TimeFormatException and a method parseTime(String) that accepts hh:mm, returns the hours and minutes, and throws the excepti...

A8 Medium

MessageTooLongException: a custom unchecked exception

Write an unchecked exception and a Messenger class whose send refuses messages longer than 160 characters.

A9 Medium

TripComputer: throwing and multi-catch

Write averageSpeed(double distance, double hours) that rejects a negative distance with an IllegalArgumentException and zero hours with an ArithmeticE...

Chapter 17 File I/O and Recursion 9 labs

L17.1 Medium

Recursion: factorial, digits and Fibonacci

Write a class Recursion with three recursive methods (no loops): [code] main reads one integer n and prints: [code]

L17.2 Hard

Words report from text

Write a class WordReport that reads one line of text and prints a small report: [code] - Words counts the words (separated by spaces); - Longest is th...

L17.3 Medium

Recursive binary search and palindromes

Write RecursiveSearch with two recursive methods: - int binarySearch(int[] a, int key, int low, int high) — prints each range it examines, look at [0....

L17.4 Medium

Towers of Hanoi

Move n disks from peg A to peg C, using B, never placing a larger disk on a smaller one. The recursive idea: move n − 1 disks out of the way (A → B),...

L17.5 Medium

Write a file, then read it back

Write CityLog in two steps: 1. static int save(Scanner in) throws FileNotFoundException reads city celsius pairs from the keyboard until the end of in...

L17.6 Easy

Recursion on strings

Write RecursiveStrings with five recursive methods — no loops anywhere: - reverse(String s); - count(String s, char c) — how many times c occurs; - co...

L17.7 Medium

Number bases, recursively

Write RecursiveBases with four recursive methods (no loops, no Integer.toBinaryString or parseInt with a base): - decToBin(int n) and decToHex(int n)...

L17.8 Medium

Find and replace in a file

ReplaceInFile corrects a word everywhere in a text file. The input gives the word to replace (line 1), the new word (line 2) and then the text. The pr...

A12 Medium

GradeReport: file input, objects and file output

Read students.txt (lines of the form id,name,grade), build Student objects, and write a formatted report.txt ending with the class average.