This repository contains my solutions and notes for the University of Helsinki's Java Programming I MOOC. The course teaches the fundamentals of programming using Java, including algorithms and object-oriented programming.
An important part of this course is completing the exercises for feedback. This repository contains the solutions I've developed for those exercises. Below are descriptions and links for each part and exercise.
Keep in mind the course's guidelines on academic honesty. You should attempt to solve each exercise yourself before consulting other implementations. Also, remember that I am learning, and these solutions might not be the best implementations.
- Notes - Contains notes taken from course materials and other sources.
- Exercise 1.1: Sandbox - Learn basic Java template use, TMC submission, and printing text.
- Exercise 1.2: Ada Lovelace - Print the string "Ada Lovelace" to the console.
- Exercise 1.3: Once Upon a Time - Print a three-line story using separate
System.out.printlncommands. - Exercise 1.4: Dinosaur - Print a three-line story using
soutshorthand for print commands. - Exercise 1.5: Message - Prompt the user for a string and print the entered message back to the console.
- Exercise 1.6: Hi Ada Lovelace! - Print "Hi " followed by the content of the
namevariable. - Exercise 1.7: Message Three Times - Prompt for a string and print it three times.
- Exercise 1.8: Greeting - Prompt for the user's name and print a greeting including it.
- Exercise 1.9: Conversation - Prompt for a greeting response, print an "interesting" remark, then ask for more details.
- Exercise 1.10: Story - Prompt for a character's name and job, then print a short story using these inputs.
- Exercise 1.11: Various Variables - Modify existing variables to print specific
int,double, andStringvalues. - Exercise 1.12: Integer Input - Prompt for an integer and then print the entered number.
- Exercise 1.13: Double Input - Prompt for a double and then print the entered number.
- Exercise 1.14: Boolean Input - Prompt for a boolean value (true/false) and print the entered boolean.
- Exercise 1.15: Different Types of Input - Prompt for a string, an integer, a double, and a boolean, then print each value back.
- Exercise 1.16: Seconds in a day - Prompt for the number of days and calculate the total seconds, then print the result.
- Exercise 1.17: Sum of two numbers - Prompt for two numbers, then calculate and print their sum.
- Exercise 1.18: Sum of three numbers - Prompt for three numbers, then calculate and print their sum.
- Exercise 1.19: Addition formula - Prompt for two integers, then print the addition formula and their sum.
- Exercise 1.20: Multiplication formula - Prompt for two integers, then print their multiplication formula and product.
- Exercise 1.21: Average of two numbers - Prompt for two integers, then calculate and print their average.
- Exercise 1.22: Average of three numbers - Prompt for three integers, then calculate and print their average.
- Exercise 1.23: Simple calculator - Prompt for two numbers, then print their sum, difference, product, and quotient.
- Exercise 1.24: Speeding Ticket - Prompt for speed; print "Speeding ticket!" if over 120.
- Exercise 1.25: Check Your Indentation - Correct indentation errors in a program demonstrating conditional statements.
- Exercise 1.26: Orwell - Prompt for a number; print "Orwell" if it is 1984.
- Exercise 1.27: Ancient - Prompt for a year; print "Ancient history!" if before 2015.
- Exercise 1.28: Positivity - Prompt for an integer; state if the number is positive.
- Exercise 1.29: Adulthood - Prompt for age; print "You are an adult" or "You are not an adult."
- Exercise 1.30: Larger Than or Equal To - Prompt for two integers; print the larger or state if they are equal.
- Exercise 1.31: Grades and Points - Prompt for points; print the corresponding course grade based on a defined scale.
- Exercise 1.32: Odd or even - Prompt for a number; print whether it is even or odd using the modulo operator.
- Exercise 1.33: Password - Prompt for a password; print "Welcome!" if "Caput Draconis", else "Off with you!".
- Exercise 1.34: Same - Prompt for two strings; print "Same" if identical, otherwise "Different".
- Exercise 1.35: Checking the age - Prompt for age; print "OK" if between 0 and 120 (inclusive), otherwise "Impossible!".
- Exercise 1.36: Leap year - Prompt for a year; determine and print if it is a leap year based on divisibility rules.
- Exercise 1.37: Gift tax - Prompt for gift value; calculate and print the gift tax based on progressive tax brackets or "No tax!".
- Exercise 2.1: Squared - Prompt for an integer, then calculate and print its square.
- Exercise 2.2: Square root of sum - Prompt for two integers, then print the square root of their sum.
- Exercise 2.3: Absolute Value - Prompt for an integer; print its absolute value.
- Exercise 2.4: Comparing Numbers - Prompt for two integers; print if the first is greater than, smaller than, or equal to the second.
- Exercise 2.5: Carry on? - Repeatedly ask "Shall we carry on?" until the user types "no".
- Exercise 2.6: Are we there yet? - Repeatedly prompt for a number until the user inputs 4.
- Exercise 2.7: Only positives - Prompt for numbers; print square of positives, "Unsuitable" for negatives, and exit on zero.
- Exercise 2.8: Number of Numbers - Read numbers until zero; print the count of non-zero inputs.
- Exercise 2.9: Number of negative numbers - Read numbers until zero; print the count of negative inputs.
- Exercise 2.10: Sum of Numbers - Read numbers until zero; print the sum of the non-zero inputs.
- Exercise 2.11: Number and sum of numbers - Read numbers until zero; print both the count and sum of non-zero inputs.
- Exercise 2.12: Average of numbers - Read numbers until zero; print the average of the non-zero inputs.
- Exercise 2.13: Average of positive numbers - Read numbers until zero; print the average of positive inputs, or "Cannot calculate the average" if none.
- Exercise 2.14: Counting - Prompt for a positive integer; print numbers from 0 up to that integer.
- Exercise 2.15: Counting to hundred - Prompt for an integer; print numbers from it up to 100.
- Exercise 2.16: From where to where? - Prompt for a starting and ending integer, then print numbers within that range; print nothing if the start is greater than the end.
- Exercise 2.17: Sum of a sequence - Prompt for an integer
n, then calculate and print the sum of numbers from 1 ton. - Exercise 2.18: Sum of a sequence - the sequel - Prompt for a starting and ending integer, then calculate and print the sum of numbers within that closed interval.
- Exercise 2.19: Factorial - Prompt for an integer; calculate and print its factorial (product from 1 to n, 0! is 1).
- Exercise 2.20: Repeating, breaking and remembering - Continuously read numbers until -1 is entered; then print the sum, count, average, and counts of even and odd numbers (excluding -1).
- Exercise 2.21: In a hole in the ground - Create a
printTextmethod that prints "In a hole in the ground there lived a method". - Exercise 2.22: Reprint - Prompt for a number
n; call theprintTextmethodntimes. - Exercise 2.23: From one to parameter - Create
printUntilNumber(int number)to print integers from 1 up to the given parameter. - Exercise 2.24: From parameter to one - Create
printFromNumberToOne(int number)to print integers from the given parameter down to 1. - Exercise 2.25: Division - Create
division(int numerator, int denominator)to print their floating-point quotient. - Exercise 2.26: Divisible by Three in Range - Create
divisibleByThreeInRange(int beginning, int end)to print numbers divisible by three within the specified range. - Exercise 2.27: Number uno - Create
numberUno()method that returns the integer value 1. - Exercise 2.28: Word - Create
word()method that returns a string of choice. - Exercise 2.29: Summation - Expand the
summethod to calculate and return the sum of its four integer parameters. - Exercise 2.30: Smallest - Define a two-parameter
smallestmethod that returns the smaller of the two integers. - Exercise 2.31: Greatest - Define a three-parameter
greatestmethod that returns the largest of the three integers. - Exercise 2.32: Averaging - Create an
averagemethod that calculates the average of four numbers by calling thesummethod. - Exercise 2.33: Star sign - Create methods:
printStars(int number)printsnumberstars;printSquare(int size)prints a square of stars;printRectangle(int width, int height)prints a rectangle;printTriangle(int size)prints a right-angled triangle, all usingprintStars. - Exercise 2.34: Advanced astrology - Create
printSpaces(int number)for spaces; implementprintTriangle(int size)to print a right-leaning triangle using spaces and stars; then createchristmasTree(int height)to print a Christmas tree with a trunk, utilizing bothprintSpacesandprintStars.
- Exercise 3.1: Third element - Read strings into a list until an empty string is entered, then print the element at index 2.
- Exercise 3.2: Second plus third - Read integers into a list until zero is entered, then print the sum of the elements at indices 1 and 2.
- Exercise 3.3: IndexOutOfBoundsException - Modify the program to intentionally cause an
IndexOutOfBoundsExceptionwithout user input. - Exercise 3.4: List size - Read strings into a list until an empty string is entered, then print the total number of strings.
- Exercise 3.5: Last in list - Read strings into a list until an empty string; print the last string entered.
- Exercise 3.6: First and last - Read strings into a list until an empty string; print the first and last strings entered.
- Exercise 3.7: Remember these numbers - Read integers into a list until -1 is entered, then print each number (excluding -1) on a new line.
- Exercise 3.8: Only these numbers - Read integers into a list until -1 is entered; then prompt for a start and end index, and print numbers within that inclusive range.
- Exercise 3.9: Greatest in list - Read integers into a list until -1 is entered, then find and print the largest number in the list.
- Exercise 3.10: Index of - Read integers into a list until -1; then prompt for a search number and print all its found indices.
- Exercise 3.11: Index of smallest - Read integers until 9999; then print the smallest number and all its indices.
- Exercise 3.12: Sum of a list - Read integers into a list until -1 is entered, then calculate and print the sum of all numbers in the list.
- Exercise 3.13: Average of a list - Read integers into a list until -1 is entered, then calculate and print the average of all numbers in the list.
- Exercise 3.14: On the list? - Read strings into a list until an empty string; then prompt for a search string and indicate if it was found in the list.
- Exercise 3.15: Print in range - Create
printNumbersInRange(ArrayList<Integer> numbers, int lowerLimit, int upperLimit)to print list elements within the specified inclusive range. - Exercise 3.16: Sum - Create
sum(ArrayList<Integer> numbers)method that returns the sum of all integers in the given list. - Exercise 3.17: Remove last - Create
removeLast(ArrayList<String> strings)method to remove the last element from the list; does nothing if the list is empty. - Exercise 3.18: Swap - Prompt for two array indices, swap their values, then print the array.
- Exercise 3.19: Index was not found - Prompt for a number to search in a predefined array; print its index if found, otherwise "was not found."
- Exercise 3.20: Sum of array - Complete
sumOfNumbersInArray(int[] array)to return the sum of all numbers in the given array. - Exercise 3.21: Print neatly - Complete
printNeatly(int[] array)to print array elements separated by a comma and space, without a trailing comma. - Exercise 3.22: Print array in stars - Complete
printArrayInStars(int[] array)to print a line of stars for each array element, with the count of stars matching the element's value. - Exercise 3.23: Print thrice - Prompt for a string, then print it three times on a single line without using a loop.
- Exercise 3.24: Check string - Prompt for a string; print "You got it right!" if "true", else "Try again!".
- Exercise 3.25: Login - Prompt for username and password; print "You have successfully logged in!" for "alex/sunshine" or "emma/haskell", otherwise "Incorrect username or password!".
- Exercise 3.26: Line by line - Read strings until empty; split each non-empty input by whitespace and print each part on a new line.
- Exercise 3.27: AV Club - Read lines until empty; for each non-empty line, split by spaces and print only parts containing "av".
- Exercise 3.28: First words - Read lines until empty; for each non-empty line, split by spaces and print only the first part.
- Exercise 3.29: LastWords - Read lines until empty; for each non-empty line, split by spaces and print only the last part.
- Exercise 3.30: Age of the oldest - Read "name,age" pairs until empty input; print the age of the oldest person.
- Exercise 3.31: Name of the oldest - Read "name,age" pairs until empty input; print the name of the oldest person.
- Exercise 3.32: Personal details - Read "name,birthYear" pairs until empty; print the longest name and the average of birth years.
- Exercise 4.1: Your first account - Create an
Accountwith 100.0 balance, deposit 20.0, then print its final balance. - Exercise 4.2: Your first bank transfer - Create two accounts ("Matthews account": 1000, "My account": 0), transfer 100 from Matthew's to My account, then print both.
- Exercise 4.3: Dog attributes - Create a
Dogclass withprivateinstance variables:name(String),breed(String), andage(int). - Exercise 4.4: Room - Create a
Roomclass withprivatecode(String) andseats(int) variables, and a constructor to initialize them. - Exercise 4.5: Whistle - Create a
Whistleclass with aprivatesound(String) variable, a constructor to set it, and asound()method to print the whistle's sound. - Exercise 4.6: Door - Create a
Doorclass with a no-parameter constructor and aknock()method that prints "Who's there?". - Exercise 4.7: Product - Create a
Productclass withname(String),price(double), andquantity(int), including a constructor and aprintProduct()method. - Exercise 4.8: Decreasing counter - Implement
decrement()to reduce the counter's value by one (but not below zero), and add areset()method to set the counter to zero. - Exercise 4.9: Debt - Create a
Debtclass withbalanceandinterestRate; implementprintBalance()andwaitOneYear()to simulate debt growth. - Exercise 4.10: Song - Create a
Songclass withname(String) andlength(int), a constructor to set them, and correspondingname()andlength()getter methods. - Exercise 4.11: Film - Create a
Filmclass withname(String) andageRating(int), a constructor, andname()andageRating()getter methods. - Exercise 4.12: Gauge - Create a
Gaugeclass with avalue(int) that increments (max 5), decrements (min 0), returns itsvalue(), and indicates iffull()(value is 5). - Exercise 4.13: Agent - Remove the
printmethod from theAgentclass and implement atoString()method to return "My name is [Last Name], [First Name] [Last Name]". - Exercise 4.14: Multiplier - Create a
Multiplierclass with a constructor taking an integer, and amultiply()method that returns its input multiplied by the constructor's number. - Exercise 4.15: Statistics - Develop a
Statisticsclass toaddNumberand trackcount,sum, andaverage. Then, use this class inMainProgramto calculate the total sum, count, and average of user-inputted numbers (ending with -1). Finally, extendMainProgramto separately sum all, even, and odd user-entered numbers using threeStatisticsobjects. - Exercise 4.16: Payment Card - Implement
PaymentCardwith balance management and transaction methods;eatmethods prevent negative balance;addMoneycaps at 150 and prevents negative top-ups;MainProgramsimulates multiple card interactions. - Exercise 4.17: Items - Read names, create and store
Itemobjects, then print them. - Exercise 4.18: Personal information - Read personal info (first name, last name, ID) until an empty first name; then print only first and last names.
- Exercise 4.19: Television programs - Read TV programs (name, duration) until empty name; then prompt for max duration and print programs within that limit.
- Exercise 4.20: Books - Read book details (title, pages, year) until an empty title; then, based on user input ("everything" or "name"), print either all details or just titles.
- Exercise 4.21: Number of Strings - Read strings until "end"; print the count of strings read, excluding "end".
- Exercise 4.22: Cubes - Read strings until "end"; for each, convert to an integer and print its cube.
- Exercise 4.23: Creating a New File - Create
file.txtin the project root via NetBeans Files tab and write "Hello, world!" into it. - Exercise 4.24: Printing a File - Read and print each line of "data.txt".
- Exercise 4.25: Printing a Specified File - Prompt for a filename, then read and print its content.
- Exercise 4.26: Guest List From a File - Prompt for a guest list filename, read names from it, then check if user-entered names are on that list.
- Exercise 4.27: Is it in the file? - Prompt for a filename and a search string; read the file and print "Found!" or "Not found!", or an error if reading fails.
- Exercise 4.28: Numbers From a File - Prompt for a filename and number range; count and print how many numbers from the file fall within that range.
- Exercise 4.29: Records From a File - Prompt for a CSV file name; read "name,age" pairs and print them as "name, age: X year(s)".
- Exercise 4.30: Storing Records - Implement
readRecordsFromFile(String file)to parse "name,age" CSV data into a list ofPersonobjects. - Exercise 4.31: Sport Statistics - Prompt for a CSV file and a team name; read match data, then print the total games played, wins, and losses for that team.
- Exercise 5.1: One Minute - Implement a
Timerclass usingClockHandwith hundredths and seconds, including a constructor,toString()for "SS:HH" format, and anadvance()method to update time. - Exercise 5.2: Book - Create a
Bookclass withauthor,title,pages, getter methods for each, and atoString()method for formatted output. - Exercise 5.3: Cube - Create a
Cubeclass with anedgeLengthconstructor,volume()method, andtoString()returning "The length of the edge is l and the volume v". - Exercise 5.4: Fitbyte - Create a
Fitbyteclass with age and resting heart rate, and atargetHeartRate()method that calculates target heart rate based on a percentage. - Exercise 5.5: Constructor Overload - Add three overloaded constructors to the
Productclass: one taking onlyname(defaulting location to "shelf", weight to 1); one takingnameandlocation(defaulting weight to 1); and one takingnameandweight(defaulting location to "shelf"). - Exercise 5.6: Overloaded Counter - Implement
Counterwith two constructors (defaulting to 0 or accepting astartValue),value()getter,increase()anddecrease()by 1, and overloadedincrease(int increaseBy)anddecrease(int decreaseBy)methods that modify the counter only ifincreaseByordecreaseByare non-negative. - Exercise 5.7: NullPointerException - Implement a program that directly causes a
NullPointerExceptionupon execution without user interaction. - Exercise 5.8: Health station - Implement a
HealthStationclass with aweigh(Person person)method that returns the person's weight, afeed(Person person)method that increases their weight by one, and aweighings()method that returns the total count of weighings performed. - Exercise 5.9: Card payments - Refactor
PaymentCardto be "dumb" with atakeMoney()method returning success; implementPaymentTerminalto handle cash payments (eatAffordably,eatHeartilyreturning change) and card payments (eatAffordably,eatHeartilytaking aPaymentCardand returning boolean success), also addaddMoneyToCardto increase card balance and terminal cash. - Exercise 5.10: Biggest pet shop - Modify
Person'stoString()method to include the associatedPet's name and breed. - Exercise 5.11: Comparing apartments - Implement methods in the
Apartmentclass:largerThanto compare total areas,priceDifferenceto return the absolute price difference, andmoreExpensiveThanto compare total prices. - Exercise 5.12: Song - Implement the
equals()method in theSongclass to compare twoSongobjects for equality based on their content. - Exercise 5.13: Identical twins - Implement the
equals()method in thePersonclass to compare all instance variables, including theSimpleDatebirthday object. - Exercise 5.14: Books - Read book names and publication years until an empty name; add new books to a list only if not already present (same name and year).
- Exercise 5.15: Archive - Read item identifier and name pairs until empty input; then print each unique item (based on identifier) at most once, using the first entered name for duplicates.
- Exercise 5.16: Dating app - Expand
SimpleDateby implementingadvance()to move the date one day,advance(int howManyDays)to move by a specified number of days, andafterNumberOfDays(int days)to return a newSimpleDateobject representing a future date without altering the original. - Exercise 5.17: Money - Implement methods for the immutable
Moneyclass:plusreturns a newMoneyobject representing the sum;lessThanchecks if oneMoneyobject's value is less than another's; andminusreturns a newMoneyobject representing the difference, or 0 if negative.
- Exercise 6.1: Menu - Implement a
Menuclass withaddMeal()to add unique meals,printMeals()to display them, andclearMenu()to empty the list. - Exercise 6.2: Stack - Implement a
Stackclass withisEmpty()to check for emptiness,add(String value)to push to the top,values()to return all elements as a list, andtake()to remove and return the topmost element. - Exercise 6.3: MessagingService - Implement
MessagingServicewith a constructor;add(Message message)to store messages up to 280 characters; andgetMessages()to retrieve the stored messages. - Exercise 6.4: Printing a Collection - Implement the
toString()method forSimpleCollectionto print its name and number of elements, listing each element on a new line if present, otherwise indicating it's empty. - Exercise 6.5: Santa's Workshop - Create a
Giftclass with a name and weight, and methods to retrieve them and atoString()for formatted output. Then, create aPackageclass to whichGiftobjects can be added, with a method to calculate and return the total weight of all gifts inside. - Exercise 6.6: Longest in collection - Implement
longest()method inSimpleCollectionto return the longest string in the collection, ornullif empty. - Exercise 6.7: Height Order - Implement a
Roomclass that canaddPersonobjects,isEmpty()to check for occupants,getPersons()to return all,shortest()to find the shortest person without removal, andtake()to remove and return the shortest person. - Exercise 6.8: Cargo hold - Implement
Item(name, weight,toString);Suitcase(max weight,addItemwith weight limit,toStringwith proper singular/plural/zero item count,printItems,totalWeight,heaviestItem); andHold(max weight,addSuitcasewith weight limit,toString,printItemsfrom all suitcases). - Exercise 6.9: Simple Dictionary - Implement a
TextUIclass that interacts with aSimpleDictionary. It should process commands: "end" to exit with "Bye bye!", "add" to prompt for and store a word and its translation, and "search" to prompt for a word and print its translation or indicate if not found. - Exercise 6.10: To do list - Implement a
TodoListclass that canaddtasks,printthem with indices, andremoveby index. Then, create aUserInterfaceclass that uses aTodoListandScannerto provide a text-based interface foradd,list,remove, andstopcommands. - Exercise 6.11: Averages - Enhance
GradeRegisterwithaverageOfGrades()to compute the average of recorded grades andaverageOfPoints()to compute the average of exam points (storing points when grades are added). Finally, integrate these averages into the user interface's output. - Exercise 6.12: Joke Manager - Create a
JokeManagerclass toaddJoke,drawJoke(randomly, or "Jokes are in short supply." if empty), andprintJokes. Then, create aUserInterfaceclass to handle user interaction (add, draw, list, stop) by utilizingJokeManagerandScanner. - Exercise 6.13: Exercises - Implement
ExerciseManagementTestandExerciseManagementclasses, developing the exercise management program using test-driven development, including refactoring.
- Exercise 7.1: Liquid containers - Implement an interactive program in
mainto manage two 100-liter containers: "first" and "second". Support "add amount" to the first (max 100L); "move amount" from first to second (respecting limits and capacity); and "remove amount" from the second (respecting limits). Print container states after each command. - Exercise 7.2: Liquid Containers 2.0 - Create a
Containerclass with methods tocontains(),add()(max 100, no negatives),remove()(min 0, no negatives), andtoString()("amount/100"). Then, rewrite the liquid container user interface from Exercise 6.1 to utilize this newContainerclass. - Exercise 7.3: Sorting - Implement five
MainProgrammethods for sorting:smallest(returns smallest value in array),indexOfSmallest(returns index of smallest value),indexOfSmallestFrom(returns index of smallest fromstartIndex),swap(swaps two elements), andsort(implements selection sort using the other methods, printing array state after each swap). - Exercise 7.4: Ready-made Sorting Algorithms - Implement overloaded
sortmethods forint[]andString[]arrays, andsortIntegersandsortStringsforArrayList<Integer>andArrayList<String>, all using Java's built-in sorting functionalities. - Exercise 7.5: Searching - Implement
linearSearch(ArrayList<Book> books, int searchedId)to find a book's index by ID sequentially, andbinarySearch(ArrayList<Book> books, int searchedId)to find a book's index by ID using the binary search algorithm on a sorted list. - Exercise 7.6: Grade statistics - Read point totals (0-100, -1 to end, others ignored); print the overall point average, average of passing points (>=50, or "-" if none), pass percentage, and a visual grade distribution (0-5) using stars.
- Exercise 7.7: Recipe search - Read recipes from a file (name, cooking time, ingredients); then, based on user commands, list all recipes, search by name (partial match), search by maximum cooking time, or search by exact ingredient match.
- Exercise 7.8: Big year - Implement a bird-watching database with commands to "Add" a bird (name, Latin name), "Observation" to record an observation for a bird (or "Not a bird!"), "All" to list all birds with observation counts, and "One" to show details for a specific bird. Handle invalid bird inputs.
A big thank you to the University of Helsinki and MOOC.fi for providing this excellent Java learning resource.
If you'd like to learn more about the course, here are some helpful links: