Course and Lab Introduction
  • course introduction on mdinfotech
  • expectations
  • the backup talk
  • logging in
  • H drive vs C drive vs Student_Collab Drive (SAVE EVERY PROGRAM YOU WRITE ON THE H (Host) DRIVE.)
  • saving and renaming files, creating folders
  • Printing
  • evaluation
There are 4 types of assessments used to help you learn to program:
  1. 100/80/60 Quizzes: short programming problems given at the beginning of class. They are used to assess if your programming skills are where they should be.
    • 60% - indicates your programming skills are not where they should be and will require a meeting with the teacher to discuss what you can do differently to succeed
    • 80% indicates your programming skills are close to what they should be you may need to adjust the way you approach your learning in this class
    • 100% indicates you have the correct solution and that your programming skills are where they should be.
    If you are not getting 100 on these quizzes, read How to be Successful in a Programming Class on the course home page.
  2. Warm-up Exercises: small exercises that take a few minutes to a couple of periods to solve and students are encouraged to keep trying until the solution is achieved. These exercises teach individual skills.
  3. Assignments: complex problems that take about a week to complete, and give you the opportunity to apply all the individual skills you have learned to a large scale problem. Programming assignments are marked against test cases that are not provided ahead of time, and your code will also be collected and assessed for formatting, commenting and chosen algorithms.
  4. Term Projects: a large scale problem that will take about 3 weeks to solve, in a group. Problem complexity will try to be matched with programmer skill. There are 2 of these projects, each worth 20% of your mark.
Get on Google Classroom
  • do course survey
  • Do Programmers Actually Need Touch Typing?
  • Test your code typing speed

  • Important Dates
    1. Canadian Computing Contest - Wed Feb 21 12-3
    2. Spring Break - March 15 to April 2
    Lesson: Resources
    To Install Eclipse at HOME:
    • Download Eclipse Installer, and follow the directions on the download page. You want to install the version "Eclipse for Java Developers".
    Test Hello World Useful Tool For CS 12's
    Read the following slides and watch the videos. The last slide has an exercise to complete with a partner. Be prepared to present to the class.
      Computer Science, Degrees, and Careers Slides

    Review the topics listed below and apply them in this exercise.

    Write a program that uses the Scanner class to read the radius of a sphere and prints the volume and surface area. Use Math.pow() and Math.PI where applicable. Catch exceptions on user input.

    Review All These Topics from CS 11:

    Review the topics listed below and apply them in this exercise.

    Modify Warm-up Exercise 1 so that if the user enters

    • characters - then print an error message that says "invalid radius" and repeats the question
    • a negative value - then print an error message that says "value must be positive" and repeat the question
    • a value greater than 1000 - then print a message that says "wow, that is big!" and continue with the calculations.
    • Review All These Topics from CS 11:
    Switch, For, Chars

    Write a for loop that iterates through each of the characters in the alphabet and uses a switch statement to identify whether it is vowel or consonant using a switch statement. The output should be something like:

                  a is a consonant
                  b is a consonant
                  c is a consonant
                  d is a consonant
                  e is a vowel
    Review All These Topics from CS 11:
    Lesson: Review Methods, New!: Overloading Methods

    Review: Methods and Defining Methods
    1. Basic Methods Introduction.
    2. Writing and Using Methods
    3. Passing Values to Methods
    4. Overloading Methods

    Create an ASCII Art Sign

    Practice in writing methods and in reusing code. Complete the assignment using the following steps. Assignment requirements must be met exactly to get full marks.

    1. Write a short main() method that calls a drawLine() method with one integer parameter. The integer is the length of the horizontal line. For example, the call drawLine(10) would print the following output:
    2. Write a method called drawSign() that takes a string parameter and prints a box around the string. For example, the call
      drawSign("Mount Douglas Secondary");
      would print the following output:
      |Mount Douglas Secondary|
      The drawSign() method must call drawLine() to draw the horizontal lines.
    3. Write a method calledhappyBDaySign() that takes two parameters. The first parameter is a string with a person's name. The second parameter is an integer with that person's year of birth. The happyBDaySign() method calls drawSign() with a Happy Birthday message created from the person's name and age. For example, the call
      happyBDaySign("Ada Lovelace", 1815);
      will call the drawSign() method with the following string:
      drawSign("Happy Birthday Ada Lovelace. You are 207 years old.");
      and the output would be:
      |Happy Birthday Ada Lovelace. You are 209 years old.|
      (Ada Lovelace is regarded as the world's first computer programmer. Look her up on Wikipedia)

      Use import java.time.Year; and to get Java to calculate the current year.

    4. Overload happyBDaySign() so that if it is called without any parameters, it automatically prints the following sign:
      |Happy Birthday Mount Douglas Secondary. You are 54 years old.|
      Mount Doug started in 1970.
    5. Write a test driver that tests EVERY method using multiple (say, at least 5) method calls and a variety of parameters.

    Lesson: Enhanced For Loop, also called a for-each loop

    Note: The enhanced for loop cannot be used for assignment because it makes a copy of the current element, and does not reference the original. Use it only when you need to access elements of the array without assigning new values.

    1. For Each Loop
    2. Enhanced For Loop

    Note: If you still have Random Board Exercise from CS 11, start with that and save yourself some coding.

    1. Write a method called getRandom2DArray that accepts an integer n. It then creates a 2D array of integers of size nxn. Populate the array with random integers between (and including) 0 and 9. Return the array.
    2. Write a method named print2DArray that accepts a 2D array on integers and prints its contents in a matrix like the one shown below. Only use the enhanced for loop. DO NOT use any traditional for loops in this method. The method will print a sample array as shown below:
           1 2 3 4
           4 3 2 1
           5 6 7 8
           9 7 6 0
    3. Write a method called findSumOfDiagonal that accepts a 2D array on integers and returns the sum of the values of its diagonal (ie. 0⊐⊏0, 1⊐⊏1, 2⊐⊏2, etc)
    4. Use this test driver to test your program:
      warm up exercise 4 test driver
    Be familiar with all Java coding conventions
  • Old Sun Code Conventions.
  • Commenting and Formatting: things to remember in all your code:
    1. Include program comments (program name, author, date, purpose).
    2. Include in-code comments.
    3. Leave a blank line before in-code comments
    4. Do not put code inside in-code comments.
    5. Label closing brackets.
    6. Indent 4 spaces after every {.
    7. Put spaces around operators and //.
    8. Use meaningful variable and method names.
    9. Create all your variables at the top of the method.
    10. Comment the purpose of every method.
    11. No spelling errors in variable names, user interface, or comments.
    12. Follow Java Coding Conventions
    Efficiency and Design
    It's good enough if my program works right?
    Your programming working is the first, and most important, thing to consider. 
    After all, a program that doesn't work is no good to anyone, and worth
    no marks.
    If you assume a program works, then is there more that should be considered?
    These principles of programming should be considered in EVERY program you write and in the following order.
    1) Readability
     Many programs will require modification by you or another coder in the future.  A poorly written program can take more time to read and understand than the actual
     modification. Programs should be written in a way that is easy to comprehend quickly.  This includes the following practices:
       a) define your variables at the top of methods
       b) comment your code
       c) use algorithms that are easy to understand. For example, avoid nested ternary operators.
    2) Reusability
      Avoid duplicating code. Always write reusable methods instead. If a modification needs to be made, it then only has to be made in one location.
    3) Efficiency
      When time permits, write algorithms that minimize the use of RAM and CPU time. For example, if you have nested for loops, does each loop need to 
      run n times, or can the inner loop run fewer times?
    4) Elegance 
      Elegance is very subjective.  However, some things are clear. Read Programming is an Art. 

    Read very carefully: Friends of Friends Assignment Description.

    How to Approach a Larger Problem Like This One:

    1. flow chart it
    2. break it down into smaller problems: make a list of functionality you need to implement, this might include a list of methods you need to write.
    3. write and test one component at a time

    Assessment (/47)

    • Test Cases (/32)
    • Code - Commenting And Formatting (/10)
    • Code - Efficiency and Design (/5)
    Lesson Slides: Classes and Objects Slides

    Topics covered:
  • Benefits of OOP
  • How to Write Classes and Objects
  • Constructors
  • get and set methods
  • Access modifiers: public vs private
  • The keyword this
  • How to Create Objects
  • Static vs non-static methods
  • Static vs non-static attributes
  • Learning Activity
    1) Watch Object Oriented Programming in 7 minutes
    2) Watch and do Classes and Objects Java Tutorial
    3) Watch and do Book Class and Constructors
    4) Watch and do Objects and Instance Methods
    5) Watch and do Get and Set Methods
    6) Watch and do Access Modifiers
    7) Watch and do Static attributes
    8) Watch and do Static Methods vs Non Static Methods
    Purpose: Design and implement a fractions class.
    Fractions can be represented as a ratio p / q where p is an integer and q is a non-zero positive integer (q > 0). Design and implement a Java class Fraction for representing such numbers. Implement the following methods:
    • Fraction() - default constructor that initializes p to 0 and q to 1.
    • Fraction(int p, int q) - a constructor that accepts p and q, and creates a new Fraction object. Make sure that the numerator p and denominator q do not have common divisors. (Hint: Do this by calculating the greatest common divisor.)
    • getNumerator() - returns the numerator
    • getDenominator() - returns the denominator
    • add() - accepts one fraction and returns the sum of this fraction and the parameter
    • multiply() - accepts one fraction and returns the product of this fraction and the parameter
    • getDouble() - returns the value of a fraction as a double
    • toString() - returns a String value of the fraction in the form numerator/denominator
    How large scale software projects should proceed is a huge area of study called the "Software Development Process". There are a number of different, often contrasting, methodologies including Agile Software Development and the Waterfall model. Although you will not be developing "large scale" projects, some of the principles of these methodologies will help you with your coding. A good overview of these principles can be found at Principles of Good Programming.
    1. Pairs Programming
    2. KISS principle
    3. DRY principle
    4. YAGNI principle
    5. Optimization
    Using the links above, answer the following questions in a Google Docs document. You will be quizzed on this material on tomorrow.
    1. What is pairs programming? How is it done? What are its benefits over individual programming?
    2. What is the KISS principle? How does it apply to writing programs for Computer Science 12?
    3. What is the DRY principle? What is the WET principle? How does DRY apply to writing programs for Computer Science 12?
    4. What is the YAGNI principle? What is the rationale behind it? How does it apply to writing programs for Computer Science 12?
    5. What is program optimization? Should it be done early or late in software development? What are the downfalls of optimization?
    remind Ms. Wear to give this quiz
    In pairs, go through this code (updated from grade 11) and explain it to each other: File Input/Output Code. Answer these question:
    1. What does getFileContents() do?
    2. What does writeArrayToFile() do?
    3. Where does filename have to be saved?
    4. What classes are used for file input?
    5. What class is used for file output?

    You will be using this code in the next assignment and will be quizzed/tested on the answers to these questions.

    Read about Ceasar Ciphers.

    Write a program that creates a random Ceasar cipher (that is, it generates a random number between 1 and 25 for the shift) for a text message. The program should read a text message from a file called message.txt. It then saves the cyphertext of the message in a file called cypher.txt. Ignore case, you can make the message caps or all lowercase. Keep spaces and punctuation as is.

    Note: Math.random() returns a random double between 0.0 and 1.0.

    Note: You must know the integer values of character values 'A', 'a', and '1' for the exam. See the Ascii table for more info.

    The Assignment

    Write a program that breaks the encryption code for a Ceaser cipher message. The program should read a cyphertext from a file called cypher.txt. It then displays the top 3 possible translations of the message in the console ranked first to third. The first is the top ranked solution. Part marks will be given for translations that rank the correct solution as second or third. Read General Program Marking Criteria. Note: solutions that take longer than 4 seconds on school computers will not be accepted.

    1. Write the code to read in the cypher from the file.
    2. Generate the 25 possible solutions and save them in an array. Ignore case, you can make it all caps or all lowercase. Keep spaces and punctuation.
    3. Process each string in the array and give it a score that represents the likelihood that it is valid English.
    4. Find the strings with the top 3 scores, and in the console, print them in order of highest score to lowest score.
    5. Efficiency and design will be considered in the evaluation.
    Breaking a Cypher

    As well as the analysis of letter frequencies, other patterns can also be detected that may help to decipher a piece of ciphertext.

    The following text explains some of the clues that can be used to deduce a word or a letter in a piece of ciphertext. If you scroll further down the page, you will see a list of tables that explain letter frequencies and patterns in the English language.

    Identify Common Pairs Of Letters: If the ciphertext appears to encode a message in English, but the plaintext does not reveal itself immediately, which is often the case, then focus on pairs of repeated letters. In English the most common repeated letters are ss, ee, tt, ff, ll, mm and oo. If the ciphertext contains any repeated characters, you can assume that they represent one of these.

    Identify The Smallest Words First: If the ciphertext contains spaces between words, then try to identify words containing just one, two or three letters. The only one-letter words in English are a and I. The most common two-letter words are of, to, in, it, is, be, as, at, so, we, he, by, or, on, do, if, me, my, up, an, go, no, us, am. The most common three-letter words are the and and.

    Tailor Made Frequency Tables: If possible, tailor the table of frequencies to the message you are trying to decipher. E.g., military messages tend to omit pronouns and articles, and the loss of words such as I, he, a and they will reduce the frequency of some of the commonest letters. If you know you are tackling a military message, you should use a frequency table generated from other military messages.

    Play The Guessing Game: Although not really applicable to this project, this can be one of the most useful skills for a cryptanalyst to employ - the ability to identify words, or even entire phrases, based on experience or sheer guesswork. Al-Khalil, an early Arabian cryptanalyst, demonstrated this talent when he cracked a Greek ciphertext. He guessed that the ciphertext began with the greeting 'In the name of God'. Having established that these letters corresponded to a specific section of ciphertext, he could use them as a crowbar to prise open the rest of the ciphertext. This is known as a crib.

    Letter and word frequencies have been analysed in a number of different languages. A few of the most commonly used ones are listed below, and may help you to decipher your secret messages. Thank-you to Daniel, who found this paper titled "English Letter Frequency Counts" which has the top 50 words in the English language and some other very interesting metrics.


    Order Of Frequency Of Single Letters

    E T A O I N S H R D L U

    Order Of Frequency Of Digraphs

    th er on an re he in ed nd ha at en es of or nt ea ti to it st io le is ou ar as de rt ve

    Order Of Frequency Of Trigraphs

    the and tha ent ion tio for nde has nce edt tis oft sth men

    Order Of Frequency Of Most Common Doubles

    ss ee tt ff ll mm oo

    Order Of Frequency Of Initial Letters

    T O A W B C D S F M R H I Y E G L N P U J K

    Order Of Frequency Of Final Letters

    E S T D N R Y F L O G H A K M P U W

    One-Letter Words

    a, I.

    Most Frequent Two-Letter Words

    of, to, in, it, is, be, as, at, so, we, he, by, or, on, do, if, me, my, up, an, go, no, us, am

    Most Frequent Three-Letter Words

    the, and, for, are, but, not, you, all, any, can, had, her, was, one, our, out, day, get, has, him, his, how, man, new, now, old, see, two, way, who, boy, did, its, let, put, say, she, too, use

    Most Frequent Four-Letter Words

    that, with, have, this, will, your, from, they, know, want, been, good, much, some, time

    Here is a dictionary if you want one: dictionary.

    remind Ms. Wear to post the quiz
    1. Get the code from Wear_IT > Pick-up > CS 12 > NewRollerBall
    2. Create a new Eclipse project.
    3. Execute the code. Examine the code and figure out how it works. You will notice this is an object oriented program with a objects ball, and table.
    4. Increase the maximum speed of the balls without breaking the graphical side of the program. A ball should still be animated somewhat smoothly across the screen. If you set the speed too fast, it will be drawn in one part of the screen, and then magically appear really far away on the next draw. If this happens, you max speed is too fast.
    5. You should start to see a bug in the program? What happens?
    6. Fix the bug in RollerBall that allows balls to escape the table boundaries. I consider it fixed if it can run for 5 minutes, with 10 balls, not escaping. Redrawing the table is not considered fixing the bug.
    7. Due Wednesday. 10/10 = fixed. 8/10 = theory about how to fix. 5/10 = no idea but tried. 0/10 = no effort.
    Read about and learn these new topics before starting this project:
    1. Arraylists
    2. Implementing Comparable and Overriding compareTo
    The Assignment:

    Create a new java project. In this project, write three classes, named OneAddress, AddressBook, and AddressBookTestCases. The first two of these classes implement the address book. The third class is a set of test cases for the first two classes. Define the variables and methods necessary to implement the address book described below.


    The class OneAddress needs to be able to store

    • last name,
    • first name,
    • street address,
    • optional second line of street address,
    • city,
    • province/state,
    • country,
    • postal code.
    All variables are private.
    • Create get and set methods for each of these
    • Create at least one constructor for the class
    • Write a toString method that returns a string that can be used as a mailing label for the address.
    • This class must implement Comparable and override compareTo so a list of OneAddresses can be sorted


    The class AddressBook stores a list of addresses in an ArrayList. This class needs to be able to add and remove addresses at any time.

    Include the following methods:

    • addAddress - Adds a new address to the address book. Use the following header:
      public void addAddress(String lastName, String firstName,
                             String address, String address2,
                             String city, String province,
                             String country, String postalCode)
    • removeAddress - Removes an address from the address book given the first and last name.
    • locationInBook - Returns index of person with the given first and last name in the address book, or -1 if they are not in the address book.
    • printAddress - Prints to the console a "mailing label" for a single address given the first and last name. It might look something like this:
        Suzy Smith
        123 Gordon Head Road
        Victoria, BC
        V2E 1J2
    • printAll - Prints to the console a list of mailing labels, sorted by last name, then first name.
    • printTable - Prints to the console a sorted by last name, then first name list where each line has three columns, last name, first name, country. The columns should all be nicely lined up. It might look something like this:
         First Name   |  Last Name  |  Country     
         Fred         |  Abersank   | Canada
         Suzy         |  Borzi      | US
         Alfred       |  Chu        | China
      Hint: Read this tutorial on String Formatting to get ideas.
    • sort - a private method that sorts the ArrayList using Collections.sort().


    The AddressBookTestCases class will test the functionality above. Here is a java source file to get you started with this class: (make sure to edit the first line to have the right package name for your own code). The method "addToBook" in that class adds several addresses to the book. In addition, write code (in appropriate places... either in main(), or in other methods, as necessary) that will do all of the following:

    • Add the following address to the address book (hint: use Mount Douglas at the first name and Secondary as the last name):
      Mount Douglas Secondary
      3970 Gordon Head Rd
      Victoria, BC, Canada, V8N 3X3
    • Remove "Darth Vader" from the address book.
    • Print out the list of names and countries three times: first before you've added Mount Douglas or removed Vader, second after you've added Mount Douglas but before you've removed Vader, and finally after you've added Mount Douglas and removed Vader.
    • Print out the mailing label for Neal Marvin.
    • Print out all of the mailing labels for all of the addresses in the address book.


    • Design your classes before you start implementing them. You may then go back and modify your design once you're implementing and realize that you need to change your design. By "design your classes", I mean sketch out the variables and methods that each class will have, including the arguments passed and the return values, but don't write the actual code inside those methods.
    • Write the purpose of each method before you write the method. That way you know what you were thinking in your design, and can use that as a reference when you're writing your code.
    • Talk to other students about the approach they are going to take. Be sure to write your own code, but just talking to one another can really help in the design process.
    • Read the ArrayList API for additional ArrayList methods ArrayList API.
    • To create an ArrayList that stores OneAddresses, use the following declaration:
      ArrayList declaration
    • Making OneAddress comparable: Read Implementing Compare To. These images may offer more help: compareTo, Collections.sort.
    Ask Ms. Wear to give the MC Quiz on Object Oriented Programming. Reminder: it's on paper in her filing cabinet.
    This assignment requires inheritance and the creation of classes Student, English, Math, History.
    Grades Calculator Assignment Description
    Ask Ms. Wear to give the Practice Exam.

    Get the space invaders code off of the Wear_IT drive.

    1. Make these EASY modifications to the game:
      • change the title of the main window
      • change the image used for the ship
      • decrease the firing interval to 300 ms
      • make the ship spawn on the left side of the screen instead of in the middle
      • change the number of aliens to 7 rows of 12 instead of 5 rows of 12
      • change the message notification when you win and lose
      • make the aliens speed up by 4% when an aliens has been killed (instead of 2%)
    2. Make these MEDIUM modifications to the game:
      • Give the ship the ability to jump up 50 px when the up arrow is pressed. It should then fall back to the ground.
      • Add a "Pause" feature that will pause the game when "P" is typed and unpause the game when "P" is typed again.
      • Change the size of the game window to 1000 px wide by 1000 wide. Update the background to fit. Modify the ship so it stops moving at the edges. Modify the aliens so they change direction when they hit the new edges. Modify the shot so it is removed once it is off the bigger screen.
      • get the aliens to shoot back
      • Create a shield that the ship can hide under for protection from aliens shooting back
    3. If you make it this far, make these HARD modifications to the game:
      • Give the ship the ability to jump up 50 px when the up arrow is pressed. It should then fall back to the ground. Use GRAVITY, and the kinematics equations, to make the jump up and fall back down look realistic.
      • add a BombEntity that is shot from the ship when the "B" key is pressed. It kills the alien it hits and all surrounding aliens.
    4. None of this is for homework. However, your understanding of the code will affect which group you are put in.
  • the game window and game loop.
  • Sprites:
    - "A small graphic that can be moved independently around the screen, producing animated effects."
  • Entities
  • Keyboard Input and Listeners
  • Collision Detection
  • Game Logic
  • Animated Aliens
  • Description

    Your group of talented programmers has been hired by Commodore to create retro computer games for their new Ultimate Gaming Machine the Commodore360. In an attempt to market to fans of the original Commodore 64, the company wants you to develop modern day versions of the classic '64 games in the modern programming language Java™. Choose the game your group would like to develop. Note: No two groups may develop the same game, and NO you may not do Space Invaders.

    What to hand in:
    1. A .jar , How to create a jar file in Eclipse
    2. Entire Eclispe project, including all code/images/classes.
    3. Banner for the webpage
    4. Video of someone playing the game to the end.

    Assessment (/100)
    1. Prototypes 1 and 2: /20
    2. Video Demo: /10
    3. Banner: /5
    4. Completed Jar File: /5
      works as standalone runnable file
    5. Game: /40
      complexity appropriate to coding skill of group, usability, design, fun-factor, challenging, graphics go together, added features to original space invaders.
    6. Code Quality: /20
      Commenting, formatting, efficiency, and design. Code used from other sources credited.
    Resources Deadlines - check Google Classroom for actual due dates
    Prototype 1: Most complicated functionality that must be added to space invaders code base working AND basic character functionality working.

    Prototype 2: Playable game.

    Final Project: Jar file, banner, demo video, and all game code and class files handed into Student Share > Wear_IT > Hand-in > CS 12 > Java Game

    40 Multiple Choice Questions on everything from this unit up to and including inheritance (and some grade 11 basics!).

    Topics include: Java platform, primitive data types, casting, objects and references, methods, overloading, algorithms, arrays, String class, API, loops, conditionals, arithmetic operators, File Input/Output, Software Engineering Principles, Classes, OOP, Constructors, instances, IDE's, compareTo, toString, ArrayList.

    No AWT or KeyInputHandler questions.