Exercises for Lesson 3
Exercise 1: Pet
Your goal is to write a class named Pet, which allows us to store information about our pets.
The Pet class should have the following methods:
Pet(name, age, kind)constructor: takesname(a string),age(an integer, in years), andkind(a string, like"dog"or"cat"), with all three as instance variablesrename(name): updates the name of a pet; returns nothingupdateAge(): updates the age when the pet has a birthday; returns nothing
Create a file Pet.kt and put your code there. To get you started, here is a main function you can use to test part of your implementation:
fun main() {
// Make a few Pet objects
val lulu: Pet = Pet("Lulu", 13, "cat")
val hobbes: Pet = Pet("Hobbes", 12, "cat")
val cheddar: Pet = Pet("Cheddar", 1, "dog")
val mal: Pet = Pet("Marshmallow", 1, "dog")
// Print some info
println("Hobbes is currently ${hobbes.age} years old, and Lulu is ${lulu.age}.")
print("The dogs are: ")
for (pet: Pet in listOf(lulu, hobbes, cheddar, mal)) {
if (pet.kind == "dog") {
print("${pet.name} ")
}
}
println()
// Hobbes has a birthday next Tuesday!
hobbes.updateAge()
println("On Tuesday Hobbes will be older! (${hobbes.age} years)")
}
Exercise 2: MyMap
If you finished Exercise 1 early, you can start Exercise 2 for fun. We won’t go over it in class.
Your goal is to write a class named MyMap, which allows us to associate keys with values. For example, we may want to map the string "blue" to the number 3 and the string "yellow" to the number 4.
The MyMap class should have the following methods:
MyMap()constructor: takes no actual parameters, but initializes necessary data structures; returnsNoneadd(key, value): adds a new mapping fromkey(assume it’s aString) tovalue(assume it’s anInt), or updates the mapping ifkeyis already present; returnsNoneget(key): looks up the value mapped to bykey; returns the value forkeyorNoneif no mapping exists forkeygetSize(): calculates the number of key-value pairs; returns that number (anint)
Think carefully about what you need to store to be able to handle any number of key-value pairs.
You should create a new file named Map.kt and put your class definition there. It should start like this:
class MyMap {
// TODO: initiailize any necessary data structures
// TODO: add methods
}Here’s a simple main function you can use to try some of the MyMap functions out:
fun main() {
val map: MyMap = MyMap()
map.add("blue", 314)
map.add("yellow", 271)
println("There are ${map.getSize()} pairs in the map.")
}How would you write code to test the rest of the class definition?