The introduction to this week was on how to write good code.
When to use camelCase, PascalCase or CAPITAL_WITH_UNDERSCORES. That would be
for variables, classes and final variables respectively. Also, the use of
indentation of each statement and line breaks between code to separate out logical
blocks.
Another important aspect related to object-oriented
programming (OOP) was to not have repeating code. If the code is repeated, then
it can have its own method/class, which is then called when needed.
The next few chapters
were about the meanings of Class, Method, Instance Variables and Objects in relation
to each other. The class being the ‘Blueprint’ and the instance variables being
the individual differences. It also goes on to say, how a constructor method is
called when a New ‘Object’ is made and how that is useful when creating
classes.
Lastly, we are introduced to the Random class in java.
Random methods allow for a (nearly) random integer to be returned. The exercises
at the end of the week were related to the use of this class.
Exercise 80: Roll the dice – A dice class needs a method ‘roll’,
which prints out (random) numbers in relation to how many sides on the dice (6-sided
dice should roll numbers 1-6).
The method “random.nextInt (x)” allows a integer variable
(x) to be given to it. And it will produce random integers between 0(inclusive)
– x(exclusive). What I found difficult about this exercise was that I did not
know how to get numbers 1-x instead. The solution was very simple.
The key here was that users will input according to standard one-based index (i.e. 6-sided dice = 1-6) while the method will use zero-based index, therefore reading ‘6’ as 0-6 (i.e.
0,1,2,3,4,5). By adding 1to the random integer, gives you the desired 1-6
output.