mdinfotech.net  



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. In-Class Exercises and Programming 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. Programming 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 Project: a large scale problem that will take about two weeks to solve, in a group or individually. Problem complexity will try to be matched with programmer skill. Each of these projects is worth 15% of your mark.
Get on Google Classroom
  • do course survey
  • Do Programmers Actually Need Touch Typing?
  • Test your code typing speed Typing.io.

  • 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
    Ms. Wear will teach a lesson that covers these questions. Answer them as the lesson is taught.

    Answer the questions in a Google Classroom document
    1. Define software.
    2. What is another word for program?
    3. Why was binary a bad way for humans to enter data into a computer?
    4. What was the first improvement on binary?
    5. What was the first high-level language?
    6. List other high-level languages.
    7. Is Java a high level or low level language?
    8. All running programs are stored in ______________.
    9. What is an operating system?
    10. List 3 categories of software and an example of each.
    11. List examples of operating systems.
    12. (Video) What does I/O stand for?
    13. (Video) What is an example of input hardware?
    14. (Video) What is an example of output hardware?
    15. (Video) What is multitasking?
    16. (Video) What is memory protection?
    Resources
    Use the Scanner class to get input from the keyboard.
    This needs to be the first line in your program:
                     import java.util.Scanner;
                     
    Create an instance of the scanner class. This goes at the top of main:
                     Scanner in = new Scanner(System.in);
                     
    To get integer data, create an integer variable at the top of main and get the input after asking the user to enter a number:
                     int x = 0;
                     ⋮
                     System.out.print("Please enter a number: ");
                     x = in.nextInt();
                     
    To get numbers with decimals, create an double variable at the top of main and get the input after asking the user to enter a number:
                     double y = 0;
                     ⋮
                     System.out.print("Please enter a number: ");
                     y = in.nextDouble();
                     
    To get a string up to the next hard return, create a String variable at the top of main and get the input after asking the user to enter some text:
                     String s = "";
                     ⋮
                     System.out.print("Please enter some text: ");
                     s = in.nextLine();
                     
    nextLine() can also be used to empty the input stream of extra characters.

    Additional methods can be found at the Scanner API

    Resource: Watch Using the Scanner Class
    1. Define the problem.
    2. Understand the problem.
    3. Formulate a solution (flow chart or a list of steps)
    4. What classes do I need to import?
    5. What variables do I need?
    6. Write the program.
    7. Test the program.
    1. Create a new program that asks the user for a mark on a test using the Scanner class. It should support decimal values since sometimes half marks are given. This should be a double.
    2. It then asks the user for the total marks possible on the test using the Scanner class. This should be an int.
    3. Finally it will display the score as a percent in the console.
    Sample Input
                      3.5
                      6
    Sample Output
                      58.33333%
                      
    In class notes
    • Arithmetic Operators (+, -, *, /, %),
    • Simple Precedence (BEDMAS, left to right),
    • Special Case for Division: Casting and Integer Division.
    Activity:
    1. Do this with a partner.
    2. Read this code JavaMath.java.
    3. Assume the user enters 10 for the first number and 7 for the second number. Write your predictions for the program output on a sheet of paper. Use your notes and the materials below to make your predictions.
    4. When you are done, complete the program.
    5. Compare your predictions to the actual output.
    6. If any of your predictions are incorrect, figure out why or ask.
    Support Materials:
    1. Arithmetic Operators, Integer Division, Casting and Modulus
    1. Create a new program that asks the user for 3 numbers. It should support decimal values. These should be doubles.
    2. It will then display the average of the three numbers in the console.
    Sample Input
                      5.5
                      6.5
                      7.5
    Sample Output
                      6.5
                      
    The first 100/80/60 Quiz.
    There are 10 kinds of people in the world, those that understand binary and those that don't.
    Watch: Representing Numbers and Letters with Binary.
    Answer the following questions in a Google Classroom Doc document during the video:
    1. What are the two possible values of a binary digit?
    2. What is the minimum value of an 8 digit binary number in binary?
    3. What is the minimum value of an 8 digit binary number in decimal?
    4. What is the maximum value of an 8 digit binary number in binary?
    5. What is the maximum value of an 8 digit binary number in decimal?
    6. Write the numbers 0 to 7 in binary.
    7. Convert the binary number: 1101101 to decimal.
    8. What is the sum of the binary numbers 1101 + 1111?
    9. What is a bit?
    10. What is a byte?
    11. Approximately how many?
      1. 1 Kilobyte = ___________bytes
      2. 1 Megabyte = ___________ bytes
      3. 1 Gigabyte = ___________ bytes
      4. 1 Terabyte = ___________ bytes
      5. 1 Petabyte = ___________ bytes
    12. Approximately how many?
      1. 1 Terabyte = _____________ kilobytes.
      2. 1 Gigabyte = _________ Megabytes.
    13. How are integers stored in a computer? What is the first bit used for?
    14. How are decimal values (or floating point values) stored?
    15. What 7-bit code was used to store letters of the alphabet?
    16. What 8-bit code replaced it to allow for 256 characters?
    17. What is the modern code that has replaced the 8-bit code?
    18. What is the ASCII value of "A"?
    19. What is the ASCII value of "a"?


    Additional Resources:
    Activity: Run this code.
           short largestShort = Short.MAX_VALUE;
           int largestInteger = Integer.MAX_VALUE;
           double largestDouble = Double.MAX_VALUE;
           System.out.println("The largest short value is " + largestShort);
           System.out.println("The largest integer value is " + largestInteger);
           System.out.println("The largest double value is " + largestDouble);
           
    Complete these steps:
    1. Now modify this code so that it also prints the MINIMUM values of a short, integer, and a double.
    2. short,int, and double are called Primitive Data Types. Look up 8 primitive data types in Java at w3Schools.
    3. Now add a variable of each type to your program (except boolean and char). Print the minimum and maximum values of each.
    4. For the boolean type, there are only two possible values. Add this code to your program:
            boolean isCSAwesome = true;
            System.out.println("isCSAwesome? " + isCSAwesome);
            
    5. Now assign isCSAwesome the other value it can store, and print its value as well.
    6. For the char type, any character can be assigned using single quotes. Add this code to your program:
            char myInitial = 'W';
            System.out.println("My last initial is " + myInitial);
            
    7. Now assign myInitial your first initial and print its value as well.
    8. This exercise will be used to complete some of the questions in the next lesson.
    Following the completion of this exericse you will understand:
  • Primitive Data Types,
  • the size of each type
  • and the relationship between maximum and minimum values.
  • Lesson in class to follow up will also cover
  • What is a variable?
  • Variable Declaration and Initialization
  • How to assign values to variables including strings and chars
  • Scope

  • Instructions

    1. Copy, paste, and answer the questions below into a Google Docs document.
    2. Use the output from In Class Exercise 3 and the links below to complete.
    3. Links to read
      1) Read Variables Tutorial.
      2) Read Variable Types Tutorial.
      3) Read Character Tutorial (You'll need the ASCII Table).
      4) Read Odd's n' Sods.

    Questions to complete:

    Variable Size, Min and Max Values
    1. Complete this table:

      Data TypeSizeMinimum ValueMax Value3 Example Values
      int4 bytes (32 bits)-31, 2, 100324333
      short
      long
      byte
      char
      boolean
      double
      float

    2. What is the relationship between the size of an integer data type and it's minimum and maximum values?
    3. List all the variable types considered to be integer types (there are 5)?
    4. List all the variable types considered to be floating types (there are 2)?
    Variable Names
    1. List all the syntax rules for naming variables:
    2. List all the conventions for naming variables:
    3. For each of the following variable names list if it is valid or invalid and explain why?
      Variable NameValid/InvalidWhy?
      num
      num1
      1num
      $num
      num 1
      num_1
      Num
      numberOne
      numberone
    4. This style of naming a variable: firstNumber, where the second word has a capital letter, is called _________________.
    5. If a variable is not named with the notation described in the previous question, will the program compile?
    Other Stuff to Know
    1. Define: scope.
    2. When assigning a variable with type char a value, what symbols must go around the value?
    3. What is the output of the following code?
      System.out.println("The Answer to the Ultimate Question of Life, the Universe, and Everything is " + 21 + 21);
      
    4. What is the output of the following code?
      System.out.println("The Answer to the Ultimate Question of Life, the Universe, and Everything is " + (21 + 21));
      
    5. Why is there a difference between the output of the above two code segments?
    6. In Java, = is not called the "equals sign", what is it called?
    7. How do you make a single line comment?
    8. How do you make a multi-line comment?
    1. Watch the following videos:
      1. Classes Part 1 (12 min)
      2. Math Class (9 min)
    2. Download MathClassSampler.java.
      1. Read, study, and try to understand the code. Predict what the program will do.
      2. Run the code, and see if you are correct about what it does. If you are incorrect, try to figure out why.
    3. Read the Math API to find the methods you need to complete the following task.
    4. Modify MathClassSampler.java by adding the following functionality:
      1. Calculate sin and cos of the same number as tan and print all 3 values with descriptive output.
      2. Calculate min of the same numbers as max and print both values with descriptive output.
      3. Calculate round of the same number as square root and print both values with descriptive output. Find the rounded value of the number entered by the user, not the rounded value of the square root.
    Tell Ms Wear to give the Computer Science 11 Software, Programming Languages, Bits/Bytes, Arithmetic, and Variables Quiz

    String Processing is using a program to analyze the properties of a string. String processing is used extensively in programming. For example, whenever you do a Google search, the string you enter into the search field must be processed to produce the search results.

    The Java API is the online documentation for all Java classes. As a Java programmer, it is imperative you learn to use the API. In this exercise you will use the String API to process a string entered by the user.

    Learn the following:
    1. Watch the following videos:
      1. Introduction to the String Class (4 min)
      2. String Class Method: charAt (7 min)
      3. String Class Method: length (6 min)
    2. Scroll to "Method Summary" in the String API to see a list of all methods you can use to process Strings.
    3. To see an example of how to use each String method, read Using String Methods with Examples. Click on the name of the string method to see an example of how to use it.

    Create a program that uses the console to ask the user to enter a favourite quote. Analyze the quote as described below. For each item in the list you will need to use one string processing method from the String API. It is your job to read the API and determine which is the best method for the job. All output must be in the console using System.out.println().

    1. Print the letter that appears at index 10. Note: If the quote has less than 10 characters this will throw an exception.
    2. Print the index of the first occurrence of the letter t.
    3. Print the number of characters in the quote.
    4. Replace every occurrence of the word "the" with "foobar". Print the new quote.
    5. Convert the entire string to all caps. Print the new string.
    6. If the quote contains the word "horse", print "I like your taste". Hint: You will need an if statement.
    Ms. Wear will likely post this as a Google Classroom exercise. Complete this activity. This material will be quizzed/tested on.
    Remember to bring a Philips screw driver. Check Classroom for the date.

    Hardware Lab
    In class notes
    • Compound Operators,
    • Increment and Decrement,
    • Precedence

    Sample code: How to Count the Number of Digits in an Integer

    int num = 654321;
    int temp = num;
    int numDigits = 0;
    
    do { 
        System.out.println(temp);
        temp /= 10;
        numDigits++;
    } while (temp > 0);
    
    System.out.println("There are " + numDigits + " digits in " + num);
    			 
    Activity - predict the output on paper, then run code to check results
    1. What is the output of this code segment?
    int i = 1;
    int j = 2;
    int k = 3;
    int m = 4;
    i += j + k;
    j *= k = m + 5;
    k -= m /= j * 2;
    System.out.println(i);
    System.out.println(j);
    System.out.println(k);
    System.out.println(m);
    
    2. What is the output of this code segment?
    int a = 1;
    int b = 2;
    int c = 3;
    System.out.println(++a * b - c--);
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    
    3. What is the output of this code segment?
    int a = 1;
    int b = 2;
    int c = 3;
    int d = 4;
    System.out.println(++b / c + a * d++);
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    System.out.println(d);
    
    Support Materials:
    1. Compound Operators
    2. Pre/Post Increment
    3. More on Pre/Post Increment
    4. Precedence
    Tell Ms Wear to give the CS 11 Variable Types, Compound Arithmetic Operators, Bytes, Hardware Quiz
    Class Discussion
    • How integers and floating point values are stored
    In Class Exercise: Round Off Error
    1. Run this program. RoundoffError.java
    2. Repeat the mathematical calculations done by the program on paper. What value do you get on paper? Does the program give the same answer?
    3. Using the links and diagram below, formulate an answer as to why the values different.
    4. Try writing a solution to the problem so the program agrees with your calculated answer.

    In your notes, summarize what Round off Error is, why it exists and how to deal with it.

    In Class Exercise: Integer Overflow
    1. Download and run MaxVariablesDemo.java
    2. Use the increment operator (++) to add one to the variables largestByte, largestShort, largestInteger, and largestLong after printing the values of each (around line 26)
    3. Immediately after increasing the value of each by one, print the values of each again.
    4. What are the new values?
    5. Using the links and diagram below, formulate an answer as to why the values are what they are.

    In your notes, summarize what Integer Overflow is, why it exists and how to deal with it.

    Resources:
    Lesson Tools

    Topics Covered:

    1. What are Binary Numbers?
    2. How does the Hexadecimal Number System work? How do you count in Hex and Binary? Watch Understanding Binary, Hexadecimal, Decimal (Base-10)
    3. How to convert Binary to Hexadecimal
    4. How to convert Hexadecimal to Binary
    5. How to convert Binary to Decimal
    6. How to convert Hex to Decimal
    7. How to do Binary Addition

    Check Your Understanding

    1. For Binary to Decimal practice, play Binary Bonanza pr Attack of the Hexadecimal
    2. For Hex to Decimal practice, play Hex to Dec Match Up Game
    Now do the Number Systems Worksheet. Remind Ms. Wear to print it.
    a) PowersCalculator
    1. Download PowersCalculator.java.
    2. Examine and run the code.
    3. Add three more METHODs: powerOfThree(), powerOfFour(), and powerOfFive().
    4. Add code to main so that the message window displays the number to the power of 2, 3,4 and 5.
    b) PlayDice
    1. Download PlayDice.java.
    2. Examine and run the code.
    3. Modify rollTheDice() so that it rolls three dice and asks the user to guess their total before they are rolled.
    4. Modify guessTheDice() so that it asks the user to guess the total of 3 rolled dice. That is, the users is to guess ONE number (not 3) between the values of 3-18. You do not need to error check the input, just assume they will follow the instructions correctly.
    5. The program should now tell the user if their guess (between 3 and 18) is correct or not.
    c) CalcAverage
    1. Use this incomplete template to write a method called average() that accepts four numbers and returns the average of those numbers. DO NOT MODIFY MAIN. Test the program thoroughly to ensure it calculates the correct average.
    Watch Boolean Expressions and the if-statement.
    1. Read if..else at W3 Schools.
    2. Read Boolean Expressions Tutorial
    3. Read Boolean Operators
    4. Do the Boolean Expressions Exercises on Classroom
    Additional Resources:
    1. Iffy Programming Tutorial
    2. Or else... Tutorial
    3. True or False?
    4. Expressions, Statements and Blocks Tutorial.
    5. Control Flow Statements Tutorial.
    1. Read this article about Boolean Methods
    2. Write a method called isLeap() that has one formal parameter: the year, and returns true if it is a leap year, otherwise it returns false.
    3. Only use if...else statements, do not use the ternary operator.
    4. Write a test driver to your method for a number of valid leap years, valid non-leap years, boundary values like 0, and extreme cases like -1, and Integer.MAX_VALUE.
    5. The rules to determine if a year is a Leap Year are:
      1. A year divisible by 4 is a leap year (2004, 2008...), unless
      2. it is also divisible by 100 (2100, 2200...) in which case it is not a leap year.
      3. There is an exception. A year divisible by 400 is a leap year (2000, 2400...).
    6. Carefully consider the order in which the above checks should be done to write a simple, accurate, algorithm

    A test driver is a main method that tests your method isLeap() with a variety of inputs to ensure it works. A sample test driver might look like this:

    			System.out.println("2000 is a leap year: " + isLeap(2000));
    			System.out.println("2001 is a leap year: " + isLeap(2001));
    			System.out.println("2002 is a leap year: " + isLeap(2002));
    			System.out.println("2003 is a leap year: " + isLeap(2003));
    			System.out.println("2004 is a leap year: " + isLeap(2004));
    			System.out.println("1800 a leap year: " + isLeap(1800));
    			System.out.println("-1 is a leap year: " + isLeap(-1));
    			System.out.println(Integer.MAX_VALUE + " is a leap year: " + isLeap(Integer.MAX_VALUE));
    	
    			
    			

    Write a test driver that proves your method isLeap() works.

    Read this website about the ?: operator, a shorter version of the if statement.

    switch statement for integers, and enumerated types like Strings, fall through, and using fall through to achieve > or <

    1. Read about the ?: operator.
    2. Read this Switch Statement Tutorial
    3. Write a method called getMaxDays(int m, int y) that has two parameters: m which is the numerical value of the month (Jan = 1, ..., Dec = 12) and y which is the year.
    4. Use a switch statement to return the number of days (that is, the return type is int) in the month (Jan has 31, Feb has 28 OR 29, ..., Dec 31)
    5. For February, use the ternary operator AND a call to isLeap to decide whether to return 28 or 29. **Note: You will need to copy and paste isLeap into the current program.
    6. If the month is not between 1 and 12, return -1. Note: -1 is an invalid number of days and indicates to the calling method that the input was invalid. It is the job of the calling method, not getMaxDays to ensure the input is valid.
    7. Write a test driver to test your method for all 12 months and boundary values such as -1, 0, and 13, and extreme values like Integer.MAX_VALUE.
    Ask Ms. Wear to give the CS 11 Control Flow Statements Quiz.

    Write code that will not crash, is user friendly, and uses dialog boxes.

    Topics include Option Panes, and Try...Catch, used with do..while and break/continue. Program along with Ms. Wear in class.

    If the user clicks "Cancel" on a dialog box, you want the program to shutdown cleanly. You will need the code below:

    
            String input;  // user input always comes in as string data
    
            // get user input
            input = JOptionPane.showInputDialog("Enter stuff!");
    
            // if the user clicks cancel, input will be null, then exit the program
            if (input == null) {
                System.out.println("You clicked cancel");
                System.exit(0);
            }
    Resources:
    1. Option Panes
    2. Catching Exceptions with Try Catch
    3. Variations on dialog boxes: JOptionPane. See this JOptionPane Tutorial for more information.
    In this exercise, you will write methods with the purpose to get input from the user, or to display output to the user. These are called Input/Output methods.
    1. Write an input method called getYearFromUser()
      • it uses a dialog box to ask the user for the year and returns the value of the year.
      • This method has no parameters
      • If the user does not enter a positive integer, the method should repeat the question until valid input is gathered.
      • It should return an int.
    2. Write an output method called showResult() that has a string as a parameter and shows the string in a JOptionPane.showMessageDialog.
    3. Use this test driver to test your methods:
                            int year = getYearFromUser();
                            showResult("You entered the year " + year);
                       

    When you are asked to hand in and print a hard copy of your code, it will be marked in two categories: Commenting and Formatting (/10) and Efficience and Design (/10). These categories are based on the software engineering principles:

    • Readability
      1. Coding Conventions
      2. Commenting
    • Usability
    • Efficiency
    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?   Wrong.
    
    Your program 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? Yes.
    
    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. 
                     
    Instructions:
    1. Copy and paste this code into a text editor.
    2. Format it according to the criteria listed above, and the Java coding conventions.
    3. Change computers with an assigned partner and assess their work /10, take one mark of for each mistake.
                  
    /*******************************
    Author: Some Badcoder
    Date: Sept 15, 2022
    ********************************/
    import javax.swing.*;
    import java.awt.Graphics;
    
    public class poorlyformatted {
    
    public static void main(String<> args) {
    String fred, stuff;
    int suzy=0;
    double george = 0;
    
    // get string input
    fred = JOptionPane.showInputDialog( "What is your name?");
       System.out.println("Hello, " + fred);   
       
    
    JOptionPane.showMessageDialog(null, "Hello, " + fred); 
    
    // get integer input
    stuff = JOptionPane.showInputDialog( "Please enter an interger:");
    
    // parse string to an integer
    try {
    suzy=Integer.parseInt(stuff);
    } catch (Exception e) {
        System.out.println("Invalid integer");
                } // catch
    
    System.out.println(suzy+" / "+2+" = "+suzy/2);   
    
    // get double input
    stuff=JOptionPane.showInputDialog( "Please enter a floating point numbar:");
    
    // parse string to a double
    try {
        george=Double.parseDouble(stuff);
            } catch (Exception e) {
                    System.out.println("Invalid double.");
                        } // catch
    
    System.out.println(george+" / "+2+" = "+george/2);   // display on console
    
    System.exit(0);
        } 
    }  // Greeting              
                  
    • All topics in this unit will be covered
    • 50 multiple choice questions
    • closed everything