30 Days of Code — Day 4
As a forcing function to get myself into the habit of writing these articles — I have decided to write an article for each day of the 30 Days of Code challenge from Hacker Rank.
The Task
Write a Person class with an instance variable, age , and a constructor that takes an integer, initialAge , as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge , the constructor should set age to 0 and print Age is not valid, setting age to 0.
. In addition, you must write the following instance methods:
- yearPasses() should increase the instance variable by .
- amIOld() should perform the following conditional actions:
If , printYou are young.
.
If and , printYou are a teenager.
.
Otherwise, printYou are old.
.
The Code
The Result
>? 2
>? 12
… You are young.
… You are a teenager.
>? 18
… You are old.
… You are old.
Conclusion
Similar to the day 2 challenge, I did not have much experience with defining a class and how the class worked together with defined functions. This exercise in particular was both challenging and enjoyable as I felt as though I learned quite a bit about programming in general, not just how to perform loops and define functions.
Here is a link to the day_3 answer/challenge I wrote about previously: 30 Days of Code — Day 3.