• lab rules, exactly what does "monitors OFF!" mean?
  • saving and renaming files, creating folders, SAVE EVERY PROGRAM YOU WRITE ON THE H (Host) DRIVE.
  • the "Back-up" talk: Google Drive and USB Sticks
  • Printing
  • Lots of 100/80/60 quizzes
  • There are a number of small programming exercises to be handed in and a few larger ones.
  • The Unit Test is worth 15% of your final mark.
  • The Group Java Game Project worth 20% of your final mark.
  • How to get an A on Programming Assignments: Program Marking Criteria
  • Test your code typing speed

Important Dates
  1. Canadian Computing Contest - Wed Feb 12 12-3
  2. Spring Break - March 14 to March 29
  3. End of Term 1 and Game Due - Friday April 3
Programming with Eclipse Resources for Installing Eclipse at Home
Other Eclipse Resources
Console Input and Output
  1. How to get user input from the command line
  2. Run this program using Eclispe:
Input and Output From Dialog Boxes
  1. Run this program using Eclispe:
Exception Handling
  1. See for example.
  2. Try Statements
  3. Official Java Tutorial on Exception Handling
  1. What is a variable?
  2. Naming Variables
  3. Numerical Variable Types
  4. Assignment
  5. Declarations and Initialization
  6. Conventions
  7. Chars
  8. Type Conversions
  9. Arithmetic Operators
    Compile and run in Eclipse:
Resources, for extra review:
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.
  1. if
  2. if..else
  3. switch
  4. conditional expression operator
  1. do..while
  2. while
  3. for
  4. enhanced for
Branching Statements
  1. return
  2. continue
  3. break
  1. Java Tutorials Control Flow Statements
  2. Iffy Programming.
  3. Or Else....
  4. True or False?.
  5. Read Switch Statement Tutorial.
  6. Going Loopy!
  7. **Enhanced For Loop (this might be a new topic for some of you)
Modify Programming 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.
  1. Basic Methods.
  2. Defining Methods
  3. Passing Values to Methods
  4. **Overloading Methods, (this might be a new topic for some of you) when more than one method has the same name, but has different parameters.

Create an ASCII Art Sign

Practice in writing methods. 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 196 years old.");
    and the output would be:
    |Happy Birthday Ada Lovelace. You are 196 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 51 years old.|
    Mount Doug started in 1970.
  5. Write a test driver that tests EVERY method using multiple method calls and a variety of parameters.
  1. Java Tutorials - Arrays
  2. Hurray for Arrays.
  3. Multidimensional Arrays
APCS Text: 6.0 Arrays, 6.6 2D Arrays
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. 

    Note: This exercise is from Grade 11. The difference is I want you to use the enhanced for loop ONLY in both print2DArray and findSum. You will need to use the traditional for loop when you populate the array with random numbers.

    Declare a 4x4 2D array of integers. Populate the array with random integers between (and including) 0 and 9. Call a method named print2DArray and pass it the above array. The method will print the array by line as shown below:

         1 2 3 4
         4 3 2 1
         5 6 7 8
         8 7 6 5
    Call a method named findSum and pass it the above array. The method will find the sum of the numbers in the array and print it.

    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)
    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?

    Not Writing the CCC - alternate activity

    Create a class called Date that includes three pieces of information as instance variables:

    • a month (type int),
    • a day (type int),
    • and a year (type int).

    Write a default constructor that sets the month and day to 1 and the year to 2000.

    Write a second constructor that initializes the three instance variables and assumes that the values provided are correct.

    Provide a set and a get method for each instance variable.

    Write a toString method that returns the day, month, and year separated by forward slashes(/). For example, Dec 10, 2021 would be written as 10/12/2021

    Write a test driver **in a separate Java file*** called DateTest that demonstrates all of the class Date’s capabilities.

    In pairs, go through this code from grade 11 and explain it to each other: Buffered Reader and BufferedWriter File Input/Output Code. Answer these question:
    1. What does in.readline do?
    2. What does out.newLine do?
    3. Why is it important to use in.close() and out.close()?
    4. Where does filename have to be saved?
    5. What class is used for file input?
    6. 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 30 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: 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.


    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.

    **ask Ms. Wear to post the quiz :)**
    1. Download
    2. Extract the zip file and create a new Eclipse project.
    3. This is a Java Applet (not an application) that was originally written to run in a website. That is why there is an html file included in the zip file. Unfortunately browsers no longer support Java Applets. You will need to run it in Eclipse.
    4. Execute the applet. Examine the code and figure out how it works. You will notice this is an object oriented program with a objects ball, and table.
    5. Uncomment the lines 63, 64, 82 and 83 in What happens?
    6. Notice the balls always bounce at a 45 degree angle. Modify so that the horziontal velocity, deltax, and the vertical velocity, deltay, are not always the same. What happens to the direction(s) of the ball(s)?
    7. Assign a random velocity to each instance of ball.
    8. 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.
    9. You should start to see a bug in the program? What happens?
    10. 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.
    11. Due Wednesday. 10/10 = fixed. 8/10 = theory about how to fix. 5/10 = no idea but tried. 0/10 = no effort.

    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 and at least one constructor for the class. Also write a toString method that prints a mailing label for the address.


    The class AddressBook needs to store a list of addresses. You will be using an ArrayList. See hints below. 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, ordered by name. (Lastname, then firstname.)
    • printTable - Prints to the console a list where each line has three columns, ordered by name: 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. See hints below.


    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.


    • Because the list of entries in the address book is dynamic (that is, entries can be added and removed), using an array to store your addresses will be clumsy. When you create an array with the new operator, it has a fixed number of entries. Instead, use an ArrayList. Look up other methods here: ArrayList API.
    • To create an ArrayList that stores OneAddresses, use the following declaration:
      ArrayList declaration
    • You will need to sort the ArrayList using Collections.sort(). This means that OneAddress will need to implement Comparable. For more information read Object Ordering. Also read Implementing Compare To. These images offer more help: compareTo, Collections.sort.
    • 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.

    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.
      • 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.
    3. If you make it this far, make these HARD modifications to the game:
      • 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.
      • get the aliens to shoot back
    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™. Visit and play some classic 64 games. 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

    56 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.