COMP 10062 - Programming in Java

ROAD MAPv1.05

Professor: dave.slemon@mohawkcollege.ca


Learning Outcomes: week1   week2   week3   week4   week6   week7   week9   week11  

Join the Class on Zoom: zoomLink




You are expected to spend 5-8 hours per week outside the classroom working on this course. Please don't come up short with this time commitment and fall behind!

Announcements


Exam Review Recommendations

Exam - When & Where

  • Tues Apr 16, 2024 at 4:30pm - 7:30pm in A211

Exam Instructions

  • This is a closed book exam all done on paper – no notes or other aids are allowed. (bring pencils, erasers and a ruler)
  • The exam is out of 102 marks.
  • You have 3 hours to complete the exam.
  • The exam consists of 19 pages.

Recommended Review:



What are Attendance Credits?    



Software Off the Shelf
(reusable java code)
Obstacles

Installing Java - on your Laptop

Important: We are using an open source version of the JDK (Java Developer Kit) in order to have the JDK bundled with JavaFX. If you download the JDK from Oracle (Java), you will not get JavaFX. For ease of ensuring both the JDK and JavaFX is installed on your system and will work when submitted, please follow these instructions.

Installing Liberica JDK and IntelliJ

Use these instructions so that you install BOTH IntelliJ and JavaFX as a bundle.



Formatting with String.format( ) and/or .printf( )

output    code (demos String.format & printf)    ( video )

Conversions

Conversions Cheat Sheet

more about conversions & examples


Javadoc Generator
Add Javadoc comments into your Java Source Files
  Javadoc comment generator



Java Code Beautifier
   java code beautifier



Online Timer


UML templates

  • UML Guidelines

  • draw.io - is a free drawing program and even has a UML menu with lots of UML tools (Recommended)

  • Here's another free piece of software for making UML diagrams: (recommended by Sam) https://umlet.com


Java starting templates




Reviewing Important Stuff from Previous Days

highlight reel
( pptx )

About the Scanner Class


Scanner Class - Reading input from console

There's a scanner reading issue when you read an integer or double and then a string; its got to do with the newline character; here's a fix: scanner and the newline issue

Scanner Class - Reading from textfiles ( source )    ( words.txt )
obstacle pic

Obstacle Problems

( rules )   

Why are we doing these obstacle questions?


Num Problem Starter
OB6 Inheritance Solution
OB5 Arrays ( Declaring & Initializing ) zip
Solution
OB4 Snowman ( Drawing tools ) zip
Solution
OB3 Dump Truck ( Array of Objects ) zip
Solution
OB2 Formatting (System.out.printf( ) and String.format( ) ) zip
video
Solution
OB1 Array of Objects Solution

Datafiles


codes.txt -- ticket bar codes

words.txt -- a dictionary of 172,710 words

small.txt -- a small 7 word dictionary

ingwords.txt  -- 12,557 words ending in ing



Great Stuff

Reusable Code

Random Number Generator
random.java -- a random number generator

EQUAL method
real-number-equals-method.java -- used to see if two real numbers are equal to each other

askQuestion method (graphics only)
askQuestion.java -- use when asking for integer input -- data validatiom

Linear Search method
linear search -- used to search an array of integers for a target

Binary Search method
binary search -- used to search an array of integers for a target BUT the array MUST be sorted

Bubble Sort method
bubble sort -- used to sort an array of integers

Quick Sort method
quick sort -- used to sort an array of integers

isNumeric(str)
isNumeric(str) -- used to determine if a string is a number

Circle Class
Circle( ) -- a Circle class

Rectangle Class
Rectangle( ) -- a Rectangle class

Dice Class
Die( ) -- a Dice class



       
Class Content Tasks Extras
(most likely not on tests/exams)

18

Final Exam Review

The following 3 questions are big fat 20+ mark final exam candidates. Get comfortable with them.

newQuestion1 - from Spec to Code    This problem has been made tougher than the one we did in class. MAKE SURE you can do this problem....

Solution: TestProgram.java   Item.java   Cart.java



newQuestion2 - from Code to UML     ( UML solution )


What we did in class today:

Today we reviewed for the exam.




17

Mouse Events


mouse events pic

Mouse Exercises
Exercise 1: mouse  ( zip )


Exercise 2:

1. each time the mouse is clicked, draw a green circle with radius 20 centred at the mouse click location

2. when the mouse is dragged, move a yellow circle.

3. change colour based on mouse button pressed
import javafx.scene.input.MouseButton;
if (me.getButton() == MouseButton.SECONDARY)


mouse_solution  ( zip )

Video 1702: Mouse Events (12:47 mins) stars
( In this video Sam explains mouse events. )


What we did in class today:

We began by reviewing ArrayList. Next, we discussed standard mouse events and did a couple of exercises. Finally, we worked on the hardware store.

Assignment #7 - Tim's Hardware Store








16 Wk 11



outcomes

guide

Exceptions

The hierarchy of Exceptions in the Java programming language begins with the Throwable class – which comes from the Object class and is its direct subclass.

Visualize Exceptions
Exceptions Object


Catching -- Responding to Exceptions
catching_exceptions.pdf   ( pptx )

Dealing with a checked exception: except1.java
  Handling the checked exception: ( fix )
  Handling all the exceptions:   ( code )   ( zip )


Throwing -- Initiating an Exception & Making your own Exceptions.
throwing_exceptions.pdf   ( pptx )



Practice Exam Question

Can you throw and catch exceptions to make this program work seamlessly without crashing?

Division Question
  starter: ( zip )
  solution: ( zip )


Exercise 1: Table Class ( zip )

Exercise 2: Pitch Counter ( zip )

Exercise 3: Circle Manager ( zip )

Video 1200: Try & Catch (15:55 mins) stars


Lecture 11.1: Catching Exceptions (30:43 mins) (Sam explains what exceptions are and how to catch them.) stars

Lecture 11.2: Throwing Exceptions (10:43 mins) (This is the best way to handle unintended errors that might occur in your class.) stars


What we did in class today: ( Mon Mar 25 2024 )

  • We introduced the concept of catching unintended user input errors, as well as other errors using the Exception class.

  • Viewed powerpoint slides regarding throwing exceptions and provided 5 example test questions on exceptions. Also included how to make your own RuntimeException.

  • Practiced on an Exam Question involving both catching and throwing exceptions. (Division_Question)



Assignment #6 - Design - Werewolves






Inspiration & Amazing Thinking


15 Wk 10

Review
Week

ArrayList

about ArrayLists   ( pptx )

ArrayList of Circles: ( code )   ( output )   ( zip )

UML Multiplicity

Polymorphism & Interfaces (a.k.a. contracts)

What we did in class today: ( Tue/Thu Mar 12/14 2024 )

  • Inspiration & Amazing Thinking: What does it mean to be: Super-locked In

  • ArrayList interactive exercise.

  • We discussed UML multiplicity: UML Guidelines

  • Build the Vehicle project. Began by creating concrete classes, then added an abstract class called Vehicle. Also added an interface called, Rollable. Concluded by building a polymorphic array of vehicles.

Inspiration & Amazing Thinking

  • James Outman on being super-locked-in
    James is a 24 year-old professional baseball player who has just earned an outfield spot on opening day for the LA Dodgers. He speaks about how he admires how his teammates are super locked in when they practice.

  • Here's an example of determination and an amazing problem solving ability. Watch how Kato perseveres and comes up with a creative solution.
    Kato pulling Braden on a Snow Sled


14 Wk 9



outcomes

guide

Abstract Classes

In Java, an abstract class is a class that cannot be instantiated and is intended to be subclassed by other classes. The main purpose of an abstract class is to provide a common interface for its subclasses while encapsulating implementation details.

Advantages of Abstract Classes

  1. Classes like Shape and GeometricObject are generic and don't really have a "look" to them.
  2. Classes can't be instantiated with the "new" statement.
  3. Abstract classes are in italics in UML diagrams
  4. Some or all of the abstract class methods can also be marked as abstract. In this case, you don't require to supply an implementation.
  5. Abstract classes can hold common code so that it doesn't need to be repeated in each subclass.
Simple Example 1
Abstract_Example_1b.zip   ( code )
Abstract classes allow you to define a common interface for a set of subclasses, while hiding implementation details that are not relevant to the interface. This helps to reduce complexity and improve code maintainability.

This example demonstrates how abstract classes can be used as a base class for other classes to inherit from. By defining common behaviour in the abstract class, subclasses can avoid repeating the same code and focus on implementing their specific functionality.

Simple Example 2
Abstract_Example_2a.zip   ( code )

Interfaces

In Java, an interface is a type that defines a contract for the behaviour of a class. An interface specifies a set of methods that a class must implement, but it does not provide any implementation itself. In other words, an interface defines what methods a class must have, but not how those methods should work.

Within the interface, you can declare any number of method signatures, but you cannot provide implementations for them.

Simple Example 1
Interface2.zip


Example 2
Bellevue1.zip
interfaces pic

Lecture 9.0: Abstract Classes (12:36 mins) stars
( In this video Sam explains abstract classes. )

Lecture 9.1: Interfaces (17:22 mins) stars
( In this video Sam explains interfaces. )

Lecture 9.2: Polymorphism Explained (20:12 mins) stars
( In this video Sam explains the concept of polymorphism. )


What we did in class today: ( Mon Mar 11 2024 )

We introduced the concept of abstract classes and interfaces. The classes we've been dealing with so far are called concrete classes. Next, we discussed Polymorphism, which comes from the Greek and means many forms.

Polymorphism

In Java, polymorphism refers to the ability of objects of different classes to be treated as if they are objects of the same class.

Polymorphism is achieved through method overriding, where a subclass provides a specific implementation of a method that is already defined in its parent class. The correct method to be called is determined at runtime based on the actual object that the method is called on.



Mixed Shapes (an example of polymorphism)

MixedShapesStarter1.zip

MixedShapesSolution1.zip    ( code )

poly pic

Assignment #4 - Cards

Figure 1. Product Shot

13 Wk 8



outcomes

guide

Inheritance week 8 guide

Java inheritance is a mechanism that allows a new class to be based on an existing class, inheriting all of its properties and behaviours. The existing class is called the superclass, and the new class is called the subclass.

Inheritance in Java is achieved using the extends keyword, which specifies the superclass that the subclass is extending. The subclass inherits all of the public and protected properties and behaviours of the superclass, and can also define its own properties and behaviours.

Animal Example
family pic
TestProgram   Animal   Bird   Dog   Cat
( zip )




Father & Son Example
family pic
Father.java     Son.java     TestProgram.java
( zip )




Example 2 - Avoiding Duplicate Code
( In this example we'll reduce repetitious code. )
after pic
After Inheritance
BeforeInheritance.zip

AfterInheritance.zip



shapes pic






Example 3 - Building a Child Target & Square Class
( In this example we'll create a Target subclass from Circle )

Start with this: TargetSquare.zip

extra challenge pic


Solution: target_square_solution.zip





Overloading ( In Java, method overloading refers to the capability of defining multiple methods in the same class or in a parent class with the same name but different parameter lists. That is, overloaded methods have the different method signatures.
  1. Same Method Name: Overloaded methods have the same name within the class.

  2. Different Parameter Lists: Overloaded methods must have different parameter lists, which can vary in terms of the number of parameters, their types, or their order.

  3. Return Type: Overloaded methods can have the same or different return types.
)

Here's an overloading_example

Overriding ( In Java inheritance, overriding refers to the capability of a subclass to provide a specific implementation of a method that is already defined in its superclass. When a subclass provides its own implementation of a method that is already present in its superclass, it is said to be overriding that method. )

When overriding...
to find the right method to run, START looking in the current class of the object and if not found work your way up the hierarchy until you find the a method within some relative (e.g. superclass).

Example: see the toString() method(s) from the Animal example




Video 800: Java Inheritance Explained (6:11 mins) stars
( In this example a Vehicle superclass is built and three subclasses are created, a Car, Bicycle and Boat. )


Lecture 8.0: Java Inheritance (26:54 mins) stars
( Sam Scott starts off discussing inheritance is general terms and then explains Example 2 above, i.e. how to reduce code via inheritance )

Lecture 8.1: Overriding (20:37 mins) stars


What we did in class today: ( Mon Mar 4 2024 )

  • we introduced the concept of Inheritance using Simple Example 1 about animals and Simple Example 2 about a father and son to demonstrate Java inheritance.
  • UML diagrams ( explained "is a" and "has a" relationships; also about arrow shapes )     Animal, Bird, Wug

  • Inheritance gives us a way to reduce repetitious code. Used the Before and After inheritance example to demonstrate.
    SimonSays: reduced code within BeforeInheritance.zip



Terminology

pic of method signature
Method Signature is the combination of a method's name and its parameter list.

Association versus Inheritance ARROWS

Association represents a relationship between two classes where one class is related to another class in some way. It is a "has-a" relationship, where one class has a reference to another class as a member variable.

For example, consider a class Car and a class Engine. The Car class may have an instance variable of type Engine, representing the engine of the car. This is an association between the Car and Engine classes.

class Car {
    private Engine engine;
    // other members and methods
}

class Engine {
    // engine-specific members and methods
}

Inheritance is a mechanism in Java that allows a class to inherit properties and behaviors (methods) from another class. It is an "is-a" relationship, where one class is derived from another class.

The derived class (subclass) inherits the members (variables and methods) of the base class (superclass). This allows code reuse and promotes the concept of hierarchical classification. In Java, inheritance is implemented using the extends keyword.

class Vehicle {
    // vehicle-specific members and methods
}

class Car extends Vehicle {
    // car-specific members and methods
}
Parent & Child

Sub-class

Test Program (main)



Assignment #5 - Tickets

Figure 1. Product Shot

IMPORTANT NOTES:

  1. Place the codes.txt file at the same level as src in your IntelliJ Project.
  2. newHere's a good example of how to write files in Java.



12



Wk 7



outcomes

guide


What we did in class today: ( Thur Feb 29 2024 )

  • Created a GUI to do morse code conversions.
  • Introduced the table class which manages tab delimited files.


Table Class

The table class manages tab delimited files.


Download: table class



Solution: PizzaSolutionGUI.zip    ( code )




11



Wk 7



outcomes

guide

Practice Question

Specifications

Solution: Square.java     myStyles.css    ( zip )



Video 700: Placing GUI Components (24:30 mins) stars

Video 701: Event Handlers (21:16 mins) stars

Video 702: Model vs View (27:43 mins) stars

Video 703:   2-D Arrays (8:50 mins)

Video 704:   Sparse Matrix Algorithm -- Triplet Algorithm (4:40 mins)


What we did in class today: ( Mon Feb 26, 2023 )

Today, we did a simon-says on the circle manager. We discussed Java based style sheets and used a stylesheet in the circle manager.

GUIs with a GraphicsContext

   more understanding about the Canvas and Graphics Context

circle gui pic

Circle Manager App


Specifications

Download the starter: starter.zip

Solution:
  CircleManager   Circle   myStyles.css    ( zip )

2-D Arrays - How to Set Them Up

Example 1: ( code  )    zip


Sparse 2-D Arrays

A matrix is sparse if many of its coefficients are zero. Many large programs in nature can been represented by sparse arrays.

sparsity =
    (count of zero elements / total element count)

Example1: Walking through 2d Array
   Traversing a 2d Array

Example2: Triplet Worksheet
   Triplet Algorithm Worksheet
   Solution: TestProgram.java


10



Wk 6



outcomes

guide

GUI - Graphical User Interface


A Baseball Pitch Counter




What we did in class: Mon Feb 12, 2024

We began by building two GUI apps. A pitch counter and a bank app. We discussed event driven handler routines and GUI component styling.

Assignment #3 - Robots

robots pic

  • Recommended: the various classes that you are required to build are SO SIMILAR to the circle.java class. That is, each class will need a .draw(gc) routine, just like the circle class has. Also, feel free to use the circle.java and rectangle.java classes if they help in building your robots.

  • Specifications

  • Class Layout

  • Hand in Requirements:

    Your submission must include just 6 files.

    1. A3.zip ( the full IntelliJ project )
    2. The following additional files are also required; but they need renaming as follows:
      • App.java.txt ( GraphicsTemplate with main pgm )
      • Head.java.txt
      • Player.java.txt
      • Team.java.txt
      • Wheel.java.txt

    Important: when you upload to canvas, you should see 6 files as mentionned above. TurnItIn needs to scan the *.txt files. Your Submitted Files should look like this.

  • Note: if you use the circle and/or the rectangle class, don't include them the *.java.txt list above.

Styling Buttons

javafx button style

Styling Text

javafx text fields

JavaFX CSS Reference Guide

CSS Guide

9



Wk 5

Draw a UML for ordering pizza. UML



class layout

Solution: Test.java    Item.java    Pizza.java





What we did in class: Mon Feb 5, 2024

We began by creating a UML for a pizza ordering app.

Next, we implemented a pizza order app.

Finally, we discussed next week's test, and introduced some more review flashcards.


Review flashcards.pptx ( pdf )

more Review flashcards.pptx ( pdf )

8



Wk 4

outcomes

guide

Draw a UML for a coin blueprint. UML






Lecture 4.3: Association (27:15 mins)

Lecture 4.4: Static (22:40 mins)


What we did in class: Thur Feb 1, 2024

We began by creating a UML for a coin class.

Next, we discussed piggybanks and created a UML for a piggybank that accepts coins.

Finally, we discussed next week's test, and introduced some review flashcards.


Review flashcards.pptx ( pdf )


7



Wk 4

outcomes

guide

Calling Constructors with this

this pic

Array of Objects

Circle   null   new   c = d

Circle Class


circles pic
  UML   zip

  Circle.java

  CircleDisplay.java

Lecture 4.1: Constructors (16:04 mins)
( Sam )

Lecture 4.2: Overloading (20:11 mins)


What we did in class: Mon Jan 29, 2024

The class began with a discussion of this.

Next, we displayed an array of circles.

Finally, we used the rest of the day to catch up from missed topics on previous days.


6



Wk 3

outcomes

guide

Visualize an Array of Objects

array pic

Owners & Pets



Create an Owner and a Pet class. Each owner has a name and is allowed to own ONE pet. The allowed pet species are dog, cat or mouse.

Each pet has a name and can make a sound. Dogs go woof, cats go meow and mice go squeak. Each pet is assigned a tag id number automatically.

Write a test program which adequately tests your new classes.

Begin by making a UML for the Owner and Pet classes

Question

Class Layout   

solution: UML   Pets.zip

Lecture 3.3: Encapsulation (25:21 mins)

Lecture 3.4: Interface vs Implementation (19:35 mins)

What we did in class: Tues & Thur Jan 23/25, 2024

We began reviewing what an array of objects looks like in memory. Next we repeated a simon-says of the BankAccount exercise from a previous class. The BankAccount problem illustrates:

  • a static class variable, i.e. nextId
  • overloaded constructors, (always write the most complicated constructor first, then use this( ) to call the complicated constructor while making the additional overloaded constructors.
  • we added some getters and setters with IntelliJ's generate tool

Next, we saw a demo of the A2-VendingMachine.

We practiced making UML's with draw.io using the Pet project as an example.

Finally, we used draw.io to make a UML for the RemoteToyHelicopter.



Remote Helicopter Class


Expect a question like this on your next test.

  • specifications

  • Draw the UML for your design.

  • Implement your UML by coding your methods into Java.

Solution:

5



Wk 3

outcomes

guide

Classes vs Objects

What's the difference between a
  
Class and an Object

object definition

Class:

  • a class is a blueprint or a template for creating objects.
  • a class defines the properties (attributes) and behaviours (methods) that objects of the class can have.
  • a class acts as a user-defined data type, allowing you to create instances (i.e. objects) based on that blueprint.

Object:

  • an object is an instance of a class.
  • an object is a tangible entity that represents a real-world thing and is created from the blueprint defined in the class.
  • an object has state (values of attributes) and behaviour (methods).

Dice Class


die pic
  UML   zip

  Die.java

  TestProgram.java




Bank Account Class

( static class variables, for next account number )

bank pic
  UML  in-memory   static

  BankAccount.java

  TestProgram.java   zip



TV Remote Control Design

Create a UML design for a TV remote control. Use draw.io or UMLet.

Video 201: What is an Object (11:36 mins) stars

Video 200: UML - Unified Modeling Language (6:53 mins) stars


Lecture 3.1: Objects and Instance Variables (40:00 mins)
( Sam explains what a class is and how it contains properties. He explains what a reference address is and how it points to a class after the new keyword is executed. Sam discusses equality of objects and warns us not to confuse equality of references with equality of objects. At the end Sam, discusses free software to draw UML diagrams. ( https://umlet.com )

Lecture 3.2: Instance Methods (24:51 mins)
( Sam explains that class methods describe the behaviour of what the class can actually do. He uses a Circle class as an example, and writes .getArea(), .getRadius( ), .setRadius( ) and .draw( ) which draws the circle on a canvas. Sam also explains more about references which point to objects.


What we did in class: Mon Jan 22, 2024

We began by defining the term class and object. We defined the term UML and discussed how it is useful in the design process.

Next, we created a histogram of 500 dice throws using the Die class.

We watched a video on Neural Pathways, to emphasize how practice and reps affect our learning.The obstacle system was explained and the first obstacle program was given out in class. (i.e. OB3). The problem needs to be submitted back to the instructor in one week.

The A2-VendingMachine today is a good example of the model and view concept. The next A2 assignment was assigned.

Assignment #2 - Vending Machine

vending machine pic

  • Specifications

  • Class Layout

  • Sample Session

  • Important Design Issues
    1. The model, i.e. VendingMachine.java, MUST NEVER communicate with the user, i.e. use System.out.print( ). All output comes from the view, i.e. Breakroom.java
    2. All displays of money, must be formatted to look like money. i.e. use System.out.printf("%.2f", moneyAmount);


  • Hand in Requirements:

    Your submission must include 4 files.

    1. A2.zip ( the full IntelliJ project )
    2. VendingMachine_UML.png
    3. Two additional files are also required; but they need renaming as follows:
      • Breakroom.java.txt ( contains your main method )
      • VendingMachine.java.txt

    Important: when you upload to canvas, you should see 4 files as mentionned above. TurnItIn needs to scan the *.txt files. Your Submitted Files should look like this.




The Value of Practice

Developing Neural Pathways



Best Guide to UML

What is a UML diagram

UML stands for Unified Modeling Language, and it is a standardized modeling language used in the field of software engineering to visualize, specify, construct, and document the artifacts of a software system. UML provides a set of graphical notations and a framework for modeling object-oriented systems.

Drawing UML diagrams


4



Wk 2

outcomes

guide

Static Methods

Static Methods ( pptx )

Method Overloading example   another example
Method overloading in Java refers to the ability to define multiple methods in the same class with the same name but different parameters. In other words, two or more methods in the same class can have the same name as long as they have a different number or type of parameters.

Middle number of 3
-- determines the middle number of 3 --
( uses method overloading )
( code )   ( zip )



Conversions Between DataTypes

Conversions

Conversions Cheat Sheet

Recommended: Always read in data from the user as a String, then convert it to what you need ...

String -> int


String -> double



int -> String


double -> String


Alternatively, when converting to String .... why not use, String.format( )

int x = 7;
String str = String.format("%d",x);


double x = 3.14;
String str = String.format("%.2f",x);

Using Arrays

hard problem pic

Question   ( code )    ( zip )



Video 40: User-defined Methods (10 mins)
Demonstrates how to create a method which is called from the main program. The method also contains 2 arguments and 2 parameters.

Video 41: Returning Information from a Method (7:15 mins)

Video 42: Guessing Game (12:35 mins)


Lecture 2.3: Switch Statement (9:33 mins)

Lecture 2.4: Do While Loop (12:05 mins)


What we did in class: Tue Jan 16 & Thurs Jan 18, 2024

We began by discussing static methods. Next, we defined the term overloading and gave a few examples of overloaded methods. Selecting the middle number of 3 also illustrated overloading.

Next, we discussed breaking up hard problems to solve into several smaller easier problems. We used an array ROTATE example to illustrate the point.

We concluded by watching a word guessing game video. In W8 we produce our own word guessing game.



Today's Worksheets ( protocol )

  • W7 - Method Overloading  (hint)



3



Wk 2

outcomes

guide

Control Statements




if pic
for pic
for pic
for pic
switch pic
for pic


Scanner's Secret Issue ( wrt to consuming the newline character left in the buffer )

When using Scanner in Java to read input, you may encounter issues with newline characters being left in the input buffer, especially when switching between reading different types of data (e.g., reading an int followed by a double).

In such cases, you can use input.nextLine() to consume the newline character and move to the next line.

Here's an example: Scanner's Secret Problem
( if you run this program you'll see the issue. To fix the issue, uncomment the scanner.nextLine(). )



JavaFX Graphics - with Circle( )

This program uses pre-built classes and illustrates how to ...

random circles

  • ask the user a question in a graphics program.
  • insist the user's response is in a given range.
  • generate random integers.
  • use an already built Circle( ) class in your graphics program.
To run this program, you'll need:
  1. RandomCircles.java
  2. Circle( ) class.
  3. getRandomInteger( ) static method.


Solution: ( code )    ( RandomCircles.zip )




Reading & Writing Text Files

Reading a File
Reading a Dictionary of 173K works called, words.txt
( code )  ( zip )


Identifying words ending in ...ING
Write a Java program to visit every word in the dictionary and display the words which end in ing. Save the ing words in a file called, INGwords.txt. Also, display the total number of words found that end in ing.
Recall, the string method .contains   This program requires the words.txt dictionary file.   ( code )   ( zip )


Picking Random 5-Letter Word
Write a Java program which displays a random 5-letter word from the dictionary.    This program requires the words.txt dictionary file.   ( code )   ( zip )


Writing to a File
This program creates and writes one line to a new text file.   ( code )


Video 30: if statements with AND ( && ) and OR ( || )(12:28 mins)

Video 31: if statements & boolean comparisons with >=, <=, !=, ==, >, <   (5:55 mins)

Video 32: Reading from Files (5:33 mins)

Video 33: Writing to Files (4 mins)


Lecture 2.1: If, While, Boolean (47:01 mins)

Lecture 2.2: For Loop (15:11 mins)


What we did in class: Mon Jan 15, 2023

We began by reaching back to class 2 and introduced Java Arrays, using the Array flash card powerpoint file. This is a stack of flashcards which you should review over-and-over until you become strong in arrays.

The Scanner class has a weird issue regarding reading ints and doubles. We discussed this issue and saw an example which illustrates what happens if you don't clear the buffer after reading an int or double and then read a String.

We began by discussing the syntax of DO WHILE. The DO WHILE loop is a good choice for validating input data. We did a Simon Says example where we used a Circle() class and a DO WHILE to generate random circles on the canvas. We then used a Rectangle() class to do the same thing. This example might help with A1-Arkanoid.

Next, we discussed the SYNTAX of various control structures, like IF, WHILE, DO WHILE, and FOR.

Lastly, we discussed the new worksheet(s).




Today's Worksheets ( protocol )

  • W4 - The Beer Song  (ans)
    (Be careful to get the last verse correct.)


MATCH the sample session EXACTLY, then add a small piece of CREATIVE code.



The New York Times - Wordl Puzzle


Today's puzzle



wordl image


The code below reads each word in the dictionary and using IF STATEMENTS narrows down the possible solution to the WORDL puzzle.

code   ( zip )



Tom Hanks - Harvard Address  


2



Wk 1

outcomes

guide

Strings & Numbers

Java Strings   ( pptx )   ( code )

Java Numbers   ( pptx )

Scope

In Java, the scope of a variable or object refers to the region of the program where the variable or object can be accessed or modified.

  Example 1: ( code )   ( zip )

  Example 2: ( code )   ( zip )

Casting

In Java, casting refers to the process of explicitly converting a value from one data type to another.

cast pic

  ( code )   ( zip )

Java Arrays

Below are flash cards with a lot of repetition to help you build and consolidate your understanding of Java arrays. Practice using the POWERPOINT file, running through these slides until you're knowledge of arrays is strong.

Array Flashcards   ( pptx )

Documentation Standards


Guide

What are packages, and what are they used for?
  ( HouseBeforePackaging.zip )

Video 20: Java Documentation (11:19 mins)

Video 21: String Functions (17:02 mins)  This video begins discussing special characters, e.g. \n, \", \\, and + Next various string methods are demonstrated, e.g. toUpperCase(), toLowerCase(), .length(), contains(), charAt(), indexOf(), substring()

Video 22: Number Functions (2.5 mins)
  ( demonstrates numeric operations, .pow(),.sqrt(),.round() )


Lecture 1.4: Data Types (34:21 mins)

Lecture 1.5: Strings (12:22 mins)


What we did in class: Tue Jan 9, or Thur Jan 11, 2023

We began by discussing string methods as well as common methods used with numbers. Block level scope was discussed. We fixed two programs that had scope error issues.

Next, we discussed casting and where and when it is commonly used.

It was emphasized that a good understanding of Arrays are essential to this course. The Array Flashcards should be mastered.

We outlined the importance of good documentation and the minimum standards required for documentation when submitting your program. Packages are a good way to organize like-minded java files.

Today's worksheet centers on mastering format strings found in printf and String.format( )



Today's Worksheets ( protocol )


MATCH the sample session EXACTLY, then add a small piece of CREATIVE code.

Assignment #1 - Arkanoid

arkanoid pic

  • Specifications

  • Required:
    • Hand in a ZIP, (i.e. A1.zip) to the myCanvas dropbox. The ZIP must contain...
      1. all of your *.java source files,
      2. any images or text files that go along with the project.
    • Alternatively, if possible, just zip up the entire IntelliJ project folder, call it A1.zip, and just submit that.


Useful Links

   String Method Cheat Sheet

   Conversions

   Java Math Class


1



Wk 1

outcomes

guide

Java Virtual Machine

The Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs.

JVM pic

You have lots of choices when it comes to selecting an editor for creating Java programs. Mohawk College has chosen to use IntelliJ.

Integrated Development Environment Software / Java - IDEs

To install IntelliJ onto your laptop it's important to follow these instructions.


Java - Output ( including graphics with JavaFX )

Data Types ( all variables must have a data type )

  • All classes/objects start with a capital letter, e.g. String, Scanner
  • All primitive types start with a lower case letter, e.g. int, double, char
  • Use camelCase for naming variables & methods,
      e.g. int secretNumber = 10;

list of primitive types

Checking for Equality: use == to compare two primitives, use a method like, .equals( ) to compare two objects.

Check out this equality example.



About System.out.print( ) & .println( )

Special characters: \t is a tab; \n is a new line

Escape characters: \\ is just a single backslash \

System.out.print( ) example.


About printf and String.format( )

(recommended: watch Video 100 )

  .printf: exercise   ( more about printf )



About Scanner ( accepting user input )


TipCalculator    ( code )
   using a static method:       ( code )

There's a scanner reading issue when you read an integer and then a string; its got to do with the newline character; here's a fix: scanner and the newline issue


JavaFX Graphics

IMPORTANT: when doing graphics, always start off with the graphics template: FXGraphicsTemplate.java
JavaFX Canvas Coordinate System: the canvas

Drawing tools
happyface   ( code )  ( zip )


Drawing lines, rectangles, ovals etc.
simple graphics   ( code )  ( zip )


Importing an Image (jpg, png etc)
the Car   ( code )  ( zip )    ( thecar.jpg )


Animation
( for animation start off with this template: FXAnimationTemplate.java )
the Moving Ball   ( code )  ( zip )

Video 100: System.out.printf( "format string", data ) explained (11:22 mins)

Lecture 1.2: Variables, Input, Output (34:58 mins)

Lecture 1.3: JavaFX Graphics (27:48 mins)
( Sam explains how to draw onto the graphics canvas. He explains how to start with a special graphics template file. Next, he draws rectangles, circles and arcs. Sam explains about changing colour with Color.web( ) method. Additional methods are discussed: setLineWidth( ), fillText( ), setFont( ), fillArc( ) )


What we did in class: Mon Jan 8 2023

We began by discussing what the JVM is and how to install it on your system at home.

Next we reviewed data types, primitives versus objects. A special discussion took place about comparing variables by contrasting == and .equals().

We empathized that the term "class" means "blueprint" and "object" means "an instance of an class".

Next, we discussed displaying output via, .print( ), .println( ) and .printf( ). We demonstrated how to accept user input using the Scanner class. A awkward adjustment was introduced regarding Scanner when reading integers followed by strings. We used the TipCalculator to demonstrate Scanner and the adjustment.

Next, we ran our first JavaFX program called, the Happyface. We looked at simple drawing tools and then discussed starting templates. Next, we ran a program which imports images as well as a program which demonstrates animation with a ball rolling across the canvas.

The expectations i.e. protocol, regarding worksheet submissions was discussed. The first two worksheets were assigned.




Today's Worksheets ( protocol )


MATCH the sample session EXACTLY, then add a small piece of CREATIVE code.






JavaFX documentation





21067 - PASS leader - (Mon & Tues): archit.archit@mohawkcollege.ca

Thursday 4p - 5p Rm: A012

Friday 12p - 1p Join Zoom Session 952 2737 7950 | PASS


PASS sessions are FREE! Attend any session that fits your schedule.

21068 - PASS leader - (Mon & Thur): robert.kumar@mohawkcollege.ca

Tuesday 10a - 11a Rm: I219

Wednesday 10a - 11a Join Zoom Session 952 2737 7950 | PASS

Friday 12p - 1p Rm: I227


PASS sessions are FREE! Attend any session that fits your schedule.