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 1231 · 84 labs

Chapter 1 Computers, Programs, and the Java Language 9 labs

L1.1 Easy

Your course card: println, print and escape sequences

Write a class CourseCard that prints exactly this card: [code] - The quotes, the backslashes and the tab after Room: and Path: must be produced with e...

L1.2 Easy

Fix the compile errors

The program below should print four lines, but it does not compile. Find and fix every error (there are five), then run it. [code] Expected output: [c...

L1.3 Easy

A café receipt with tabs

Write a class Receipt that prints this receipt for the campus café. Use \t (tabs) to align the prices, and let Java compute the total (12.00 + 18.50 +...

L1.4 Easy

Let Java do the arithmetic

Write QuickMath: eight println statements, each printing a label and a value that Java computes (do not type the results yourself). The program takes...

L1.5 Easy

Rocket launch: backslashes and print

Write Rocket, which prints this picture and countdown (no input): [code] - Every backslash in the picture must be written \\ inside a Java string. - T...

L1.6 Easy

It compiles, but the answers are wrong

The program in the editor compiles and runs, yet five of its six results are wrong: these are logic errors, the kind the compiler cannot find. Fix the...

L1.7 Easy

A table of squares and cubes

Write SquaresTable, which prints a small table. The columns are separated by a tab (\t), and every square and cube is computed by Java (3 3, 3 3 3) —...

L1.8 Easy

Average speed of a cyclist

A cyclist rides 24 km in 1 hour 15 minutes and 30 seconds. Write AverageSpeed, which lets Java compute the speed step by step, using only println and...

L1.9 Medium

A sum, and an approximation of π

The number π can be approached by the series 4 × (1 − 1/3 + 1/5 − 1/7 + 1/9 − 1/11 + …): the more terms, the closer. Write SeriesPi, which prints exac...

Chapter 2 Algorithm Design: Pseudocode, Flowcharts, and Tracing 9 labs

L2.1 Easy

From pseudocode to Java: temperature converter

Translate this pseudocode into a Java class TempConvert: [code] Read a real number and print it as 25.0 C = 77.0 F = 298.15 K (1, 1 and 2 decimals, us...

L2.2 Medium

Design an algorithm: how much paint?

A room has length, width and height (meters). One door (2 m²) is not painted. One liter of paint covers 10 m² and costs 45.5 yuan. 1. Write the algori...

L2.3 Medium

Trip planner: hours, minutes and arrival time

Write TripPlanner. It reads three integers: a distance (km), an average speed (km/h) and the departure time in minutes after midnight (e.g. 510 = 8:30...

L2.4 Easy

Running pace: from an algorithm to a program

A runner enters a distance in km and a time in minutes and seconds. Design the algorithm first (input → steps → output), then write RunPace: [code] Fo...

L2.5 Easy

Splitting the bill

Friends share a restaurant bill equally and add a tip. Write the algorithm in pseudocode, then the program SplitBill: read the bill, the tip in percen...

L2.6 Easy

Egg cartons: whole numbers and remainders

A farm packs eggs in cartons of 12. Write EggCartons: read a number of eggs and print how many cartons are full, how many eggs are left over, how many...

L2.7 Easy

Cost of a road trip

Four friends share the fuel of a road trip. Write the algorithm first, then the program RoadTrip. [code] For the input [code] the program prints (two...

L2.8 Easy

A cylindrical water tank

A village wants to buy a cylindrical water tank and paint its wall. From the radius and the height in metres, WaterTank prints the base area, the volu...

L2.9 Medium

Take-off: how long must the runway be?

A plane accelerates steadily from rest until it reaches its take-off speed. Physics gives: [code] Runway reads the take-off speed in m/s and the accel...

Chapter 3 Java Basics: Class Structure, Variables, and Data Types 9 labs

L3.1 Easy

Sum and average of three numbers

Write a class Numbers that reads three integers from the keyboard and prints: - their sum, as Sum: 12 - their average with two decimal places, as Aver...

L3.2 Easy

Swap two variables

Write SwapValues: read two integers a and b, print them, swap their values using a third variable, and print them again. Then swap them back without a...

L3.3 Easy

Student ID card: reading different types

Write StudentCard. Read, in this order: a name (one word), an ID (int), the credits earned (int), the GPA (double), the section letter (char) and whet...

L3.4 Medium

When int is not big enough: overflow

Write Overflow: read two integers and print their product computed as int, as long (widening before multiplying), and widened after multiplying: [code...

L3.5 Easy

Unit converter with named constants

Write UnitConverter with three named constants (public static final double): KM_PER_MILE = 1.609344, KG_PER_POUND = 0.45359237, CM_PER_INCH = 2.54. Re...

L3.6 Medium

A light-year: choosing between int, long, double and float

Light travels 299 792 458 metres per second. Write LightYear with that value as an int constant SPEED_OF_LIGHT. Read a number of light-years (a double...

L3.7 Medium

Population projection with constants

In a region there is one birth every 40 seconds, one death every 95 seconds and one new arrival every 120 seconds. Population reads the current popula...

L3.8 Easy

Energy to heat water

Heating 1 kg of water by 1 °C takes 4184 joules. HeatWater reads the mass of water in kg, its starting temperature and the final temperature, and prin...

L3.9 Medium

Tax to the cent: the type cast

A cash register must turn a computed tax such as 11.853 into cents. TaxCents reads a price and a tax rate in percent, and prints: 1. the tax exactly a...

Chapter 4 Operators, Expressions, and Type Conversion 9 labs

L4.1 Easy

Seconds into hours, minutes and seconds

Write a class TimeSplit that reads a number of seconds (a positive int) and prints it as hours, minutes and seconds, exactly in this form: [code] Use...

L4.2 Medium

Change maker: coins and notes

Write ChangeMaker. Read a price and the amount paid (both with cents). Print the change and how to give it with the fewest notes/coins of 10, 5, 1, 0....

L4.3 Medium

Savings: simple vs. compound interest

Write Savings. Read a principal, an annual interest rate in percent and a number of years. Print the final amount with simple interest P(1 + r·t), com...

L4.4 Easy

Digits of a four-digit number

Write Digits: read a four-digit integer (1000–9999) and print its digits, their sum, the number reversed, its last two digits and whether it is divisi...

L4.5 Medium

How long is the class?

Write ClassLength. Read a start time and an end time as hours and minutes (8 30 9 45) and print the length in minutes, in hours and minutes, and as a...

L4.6 Medium

Predict, then run: compound and increment operators

Write OperatorTrace. Read two integers a and b, set x = a, then execute exactly these statements, printing the variables after each one: [code] and fi...

L4.7 Easy

Calendar and clock arithmetic with %

Days of the week are numbered 0 (Sunday) to 6 (Saturday), and hours 0 to 23. ClockMath reads today's day number, a number of days ahead, the current h...

L4.8 Easy

One billion minutes

MinutesToYears reads a number of minutes (a long, it may be very large) and converts it into years (of 365 days), days, hours and minutes. It also pri...

L4.9 Medium

Free fall and the 1 / 2 trap

An object dropped from rest falls a distance d = ½ g t² and reaches the speed v = g t (g = 9.8 m/s²). FreeFall reads the time in seconds and prints: -...

Chapter 5 Characters, Strings, and Console Input 9 labs

L5.1 Easy

Initials and vowels in a name

Write a class NameTool that reads a full name on one line (for example hamza djigal) and prints: - the initials in capitals, as Initials: H.D. - the n...

L5.2 Easy

Email address parts

Write EmailParts: read an email address (one line), trim it and convert it to lower case, then print the user name, the domain, the extension (after t...

L5.3 Easy

Formatting a name

Write NameFormat: read a full name first last (any capitalization, one space between) and print the formal form, initials, a username (first letter +...

L5.4 Easy

Characters are numbers too

Write CharInfo: read one character and print its Unicode code, the next and previous characters, whether it is a letter or a digit, and its upper/lowe...

L5.5 Medium

Reformat a date

Write DateReformat: read a date in ISO format yyyy-mm-dd and print it in four formats: [code] Get the month name without if or switch: store "JanFebMa...

L5.6 Easy

Masking a bank card number

Receipts never show a whole card number. Write CardMask: read one line containing a 16-digit card number that may be typed with spaces or dashes (6222...

L5.7 Easy

File name inspector

FileName reads one line containing a file name (it may contain spaces and always contains a dot) and prints facts about it, using only String methods...

L5.8 Medium

A secret word: arithmetic on letters

The Caesar cipher replaces each letter by the letter shift places further in the alphabet, going back to A after Z. CaesarWord reads a word of exactly...

L5.9 Easy

Comparing two words

CompareWords reads two words and prints how Java compares them: their lengths, equals, equalsIgnoreCase, compareTo, compareToIgnoreCase, whether the f...

Chapter 6 Selection and Boolean Logic 9 labs

L6.1 Easy

Letter grade with validation

Write a class Grade that reads a score (an int) and prints the letter grade: Score Grade --- --- 90–100 A 80–89 B 70–79 C 60–69 D 0–59 F Print it as G...

L6.2 Medium

Days in a month (leap years)

Write a class DaysInMonth that reads a year and a month (1–12) and prints the number of days, as Days: 29. A year is a leap year when it is divisible...

L6.3 Medium

Museum ticket prices

Write TicketPrice. Read an age, whether the visitor is a student (true/false) and the day (Mon … Sun). Rules: - age < 0 or 120 → print Invalid age and...

L6.4 Medium

Triangle classifier

Write TriangleType: read three side lengths (integers). If they cannot form a triangle (a side ≤ 0, or the sum of two sides ≤ the third), print Not a...

L6.5 Easy

Electricity bill with tiers

The city charges electricity in tiers: the first 200 kWh at 0.55 yuan, the next 200 kWh at 0.60, and everything above 400 kWh at 0.85. Write Electrici...

L6.6 Medium

Rock, paper, scissors referee

Write RockPaperScissors: read the moves of player 1 and player 2 (rock, paper or scissors, in any letter case) and print the result: - Invalid move: l...

L6.7 Easy

Three numbers in order, with if and swap

SortThree reads three whole numbers and prints them in increasing order, then the smallest, the middle and the largest, and finally whether all three...

L6.8 Medium

The check digit of an ISBN-10

An ISBN-10 book number has nine digits d1…d9 followed by a check digit: [code] If the result is 10, the check digit is written X. Isbn10 reads the fir...

L6.9 Medium

Where is the point?

PointPosition reads the coordinates x y of a point and answers three questions: 1. Is it inside, on the border of, or outside the circle of centre (0,...

Chapter 7 Loops and Iteration 9 labs

L7.1 Medium

Multiplication table

Write a class Multiplication that prints the multiplication table from 1 to 9 as a neat grid, using nested loops. Each number must be printed in a fie...

L7.2 Medium

Reading until a sentinel

Write a class Sentinel that reads integers until the user types -1, then prints: [code] The sentinel -1 is not part of the numbers. If no number was e...

L7.3 Medium

Guess the number

Write GuessGame. The first input is the secret number (in a real game it would be random); then come the player's guesses. For each guess print 40 is...

L7.4 Medium

The Collatz sequence

Start with a positive integer n. If n is even, divide it by 2; if odd, replace it by 3n + 1. Repeat until n = 1 (mathematicians believe this always ha...

L7.5 Medium

Patterns with nested loops

Write Pyramid: read n and print a right triangle of stars, an empty line, and a number pyramid: [code] (for n = 4). Use nested for loops: the outer lo...

L7.6 Medium

How long until the savings goal?

You deposit the same amount at the end of every month in an account that pays interest monthly. Write SavingsGoal: read the goal, the monthly deposit...

L7.7 Medium

The two best scores, without an array

TwoHighest reads the number of students n (at least 2), then n lines name score (scores from 0 to 100). It prints the student with the highest score,...

L7.8 Medium

Decimal to binary with a loop

ToBinary reads whole numbers until a negative number ends the input. For each number it prints its binary form, the number of bits and how many of the...

L7.9 Medium

Prime factors

Every whole number from 2 up is a product of prime numbers: 360 = 2 × 2 × 2 × 3 × 3 × 5. PrimeFactors reads a number (at least 2) and prints this deco...

Chapter 8 Methods and the Java API Library 9 labs

L8.1 Medium

Prime numbers

Write a class Primes with a method [code] that returns true when n is a prime number (1 and every number below it are not prime). The main method read...

L8.2 Medium

gcd and lcm

Write a class MathTools with two static methods: [code] gcd returns the greatest common divisor (use Euclid's method: while b is not 0, replace the pa...

L8.3 Medium

Palindromic numbers with methods

Write Palindromes with three methods: reverse(int n) returns n with its digits reversed, isPalindrome(int n) uses reverse, and digitCount(int n) count...

L8.4 Easy

BMI report with reusable methods

Write BmiReport with methods bmi(weightKg, heightCm), category(bmi) (Underweight < 18.5 ≤ Normal < 25 ≤ Overweight < 30 ≤ Obese), weightFor(targetBmi,...

L8.5 Medium

Dice simulator with java.util.Random

Write DiceLab with the methods rollDie(Random random) (returns 1–6), and bar(int count) (returns that many ). main reads a seed and a number of rolls,...

L8.6 Medium

Password rules, one method per rule

A site accepts a password only if it (1) has at least 8 characters, (2) contains only letters and digits, (3) contains at least 2 digits and (4) conta...

L8.7 Hard

Is this card number valid? The Luhn check

Card numbers (13 to 16 digits) carry a built-in check, the Luhn algorithm: 1. From the right, double every second digit; if the result has two digits,...

L8.8 Medium

Your own square root: the Babylonian method

Long before computers, square roots were computed by repeating one formula: if guess is an approximation of √n, then [code] is a better one. Start wit...

A1 Medium

MyTriangle: methods, validation and formatted output

Write a class MyTriangle with two static methods: isValid(double s1, double s2, double s3), returning true when the three lengths can form a triangle...

Chapter 9 Arrays and Two-Dimensional Arrays 12 labs

L9.1 Medium

Statistics of an array

Write a class Stats that reads a count n, then n integers into an array, and prints: [code] Write the minimum and the maximum with your own loop — do...

L9.2 Medium

Reverse an array and search in it

Write a class ArrayTools with two static methods: [code] The main method reads a count n, then n integers, then one value to search for. It prints the...

L9.3 Hard

Row and column sums of a matrix

Write a class MatrixSums that reads two integers rows and cols, then rows × cols integers into a two-dimensional array, and prints the sum of each row...

L9.4 Medium

Two weeks of temperatures

Write TempStats. Read n, then n daily temperatures into a double[]. Print: [code] - Days are numbered from 1 for the user, but the array starts at ind...

L9.5 Medium

Cinema seat booking with a 2D array

A small cinema has 5 rows (A–E) of 8 seats. Write CinemaSeats using a boolean[][]. Read booking requests such as B 4 until the word END; for each prin...

L9.6 Medium

Tic-tac-toe referee

Write TicTacToe. Read a 3 × 3 board as three words of three characters (X, O or . for empty) into a char[][]. Write the methods wins(char[][] board, c...

L9.7 Medium

Distinct numbers

Distinct reads n, then n whole numbers, and prints how many different values there are, the different values in the order of their first appearance, a...

L9.8 Medium

Merging two sorted lists

Two class sections each hand in a list of scores already sorted in increasing order. MergeSorted reads the first list (its length, then its values) an...

L9.9 Hard

Sudoku referee

A Sudoku solution is a 9 × 9 grid in which every row, every column and every 3 × 3 box contains the digits 1 to 9 exactly once. SudokuCheck reads the...

A2 Medium

findMode: the most frequent value of a sorted array

Write public static int findMode(int[] array) returning the value that occurs most often in a sorted array. If several values tie, return the first. T...

A3 Medium

leastFrequent: the rarest element of an unsorted array

Write public static int leastFrequent(int[] arr) returning the element that occurs the fewest times; if several tie, return the one appearing earliest...

A4 Medium

Matrix addition

Compute and print C = A + B for A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] and B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]].

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.