Table of Contents
Homework 1.1 - Computer Representation of Data
-
Write the following numbers in binary:
0476
,0x2A3F
,0xBDAE
. The numbers are written either in octal or hex. You can distinguish octal from hex because, by convention, hex numbers are written beginning with “0x” while octal numbers are written beginning with a zero only. For example:0476
means the octal number476
. You can tell it is an octal number because it begins with “0” but not “0x.”0x2A3F
means the hex number2A3F
. You can tell it is a hex number because it begins with “0x.”438
is a decimal number because it doesn’t begin with “0” or “0x.”
-
Write each of the following binary numbers in both octal and hex:
011011101010
,1101000110
,000101111
. Follow the convention mentioned above when writing your octal and hex numbers. -
Write the following binary numbers in decimal:
1
,10
,11
,100
,101
,110
,1000
,1010
,1000001
,0000101
. -
Write the following hex numbers in decimal:
0xBDAE
,0x99
,0x2A3F
,0x87
. Notice that because 16 is larger than 10, some numbers can be e xpressed using fewer digits in base 16 than in base 10. -
Write each of the following decimal numbers in binary, octal, and hexadecimal:
8
,16
,63
,64
,128
. Follow the convention mentioned above when writing your octal and hex numbers -
Write the binary representation of ‘A’ (capital A) in both ASCII and 16-bit Unicode. Show all bits in each encoding. Recall that ASCII is an 8-bit code. The ASCII code is shown below.
-
Java uses 16-bit Unicode. Write the binary representation of the word ‘Apple’ as it would be stored in memory by a Java program.
-
What text is represented by the following binary characters?
01010100 01101111 00100000 01100010 01100101 00100000 01101111 01110010
00100000 01101110 01101111 01110100 00100000 01110100 01101111 00100000
01100010 01100101
Homework 1.2 - Counting with Loops
Write a Java program that will print the following to the screen. A starting point will be provided to you in GitHub. Please read the comments in the GitHub files.
-
Print out the even numbers from 2 to 100 (inclusive).
-
Print out odd numbers from 1 to 99 (inclusive).
-
Print out the powers of 2 from 1 to 4096.
Homework 1.3 - Traveling Circles
In class we saw how to create simple animations using setup()
and
draw()
. Write a program in Processing that will create a circle that
will travel clockwise around the edge of the screen, starting at the top-left
corner.
Homework 1.4 - Looping Sums
Write a Java program that will print the following to the screen. A starting point will be provided to you in GitHub. Please read the comments in the GitHub files.
-
Using a loop, calculate and print out the sum of all integers from 1 to 100 (inclusive).
-
Using a loop, calculate and print out the sum of \(1 + \frac{1}{2} + \frac{1}{3} + \cdots + \frac{1}{100}\) using
float
. -
Using a loop, calculate and print out the sum of \(\frac{1}{100} + \frac{1}{99} + \cdots + \frac{1}{2} + 1\) using
float
.
Homework 1.5 - Drawing Grids
Write a Processing program to create a 600x400 window and then draw
horizontal and vertical lines to divide the window into an evenly
spaced grid. Your program should rely on a variable n
such that
each the grid is made up of n vertical and n horizontal rectangles.
For example, if n=3
, your program should draw four lines to divide
the window into nine squares like this. Try your program with a few
different values of n
.
Note: The project starter will save images of each grid you produce. Please include those images in your submission.
Homework 2.1 - Representing Floating Point Numbers
- Consider a simple 16-bit floating point format that uses one bit to indicate sign (1 means negative), 11 bits for the mantissa, and 4 bits for an exponent stored in two’s complement format. The bits are stored left to right in the above order; i.e., the sign bit is leftmost and the exponent bits are rightmost. What numbers are represented by these bits?
1101 0100 0000 0110
0000 0000 0001 1000
0000 0000 0000 0000
- Using the above floating point format, write the binary representation for these decimal numbers. (Note: some of these numbers may not be representable in binary. If so, please state that fact and use the closest approximation you can create in this 16-bit format):
- -0.125
- 4.5
- 1/3
- 0.1
- Choose three more decimal numbers and write their floating point binary representations.
Homework 2.2 - Graphing Functions
If you wanted to graph a function on graph paper by hand, you would typically build a table of x
and y
values, plot each of those points on your graph paper, and then use your artistic skills to create smooth lines joining the points. The closer together each of your points was, the easier it would be connect the dots. Graphing an equation in Processing works much the same way, except when Processing tries to connect the dots, it will only use perfectly straight lines. To get something that looks like a smooth curve, you will need to approximate it with many very short line segments.
Using a window size of 400x400, graph the following functions.
- \[y = \frac{1}{2} x + 40\]
- \[y = x^2\]
- \[y = 100 \sin(\frac{x}{10})\]
- Choose your own function and graph it.
Homework 2.3 - Sierpiński Triangle
The Sierpiński triangle is a famous fractal that can be constructed by recursively diving equilateral triangles into four sub-triangles by joining the midpoints of each side of the triangle. Because it is a fractal, this recursion can be performed inifinitely, but we don’t have that much time to wait. Please write a Processing program that will draw the Sierpiński triangle after 10 iterations of recursion.
The end result will look something like this.
Homework 2.4 - TBD
Homework 2.5 - TBD
Homework 3.1 - Penner's Easing Functions
In 2002 Robert Penner, who would go on to work for Adobe on the team developing Flash, wrote a book on computer animation in Flash. In one chapter of his book, he described the concept of “Tweening” and “Easing”. In the days of traditional animation, Tweening referred to the work done by more junior animators to draw out the individual frames between the keyframes drawn by a more senior animator. In computer animation, tweening works much the same way, but the computers are using math to interpolate what these intermediary frames should look like.
We can think of animated motion as treating position as a function of time. From physics, for linear motion, we have the equation \(x = v t + x_0\). But objects in the real world don’t generally have constant acceleration. It will take some time for a parked car to reach highway speeds when the driver puts their foot on the pedal. In his book, Penner described a series of “easing” functions that allowed for more dynamic position functions such as “easing in”, the object slowly accelerates to a constant speed, “easing out”, the object starts fast and slows down towards the end of its path, and several others. These functions have become standards today in many computer animationtools.
Each of the equations takes the following form:
getTweenPosition (time, begin, change, duration) {
// calculate position here
return position;
};
Because they all have this same form, we can model them as simple objects and rely on polymorphism to use them. In the starter project provided with this assignment, three of the easing functions have been implemented as classes. Your task is to implement 7 other functions of your choice. Try to name your classes intuitively. The full list of equations can be found here.
To make it easier to visualize the easing functions, the first three have been rendered as a monochrome gradient with three equal vertical stripes, one for each easing function. Create an gradient like this with 10 equal stripes, one for each easing function.
Homework 3.2 - Racing Cars
In class, we saw how to draw animated cars using objects. Each car had a
position and a speed. Modify the car object so that it also has a color property. Then fill in the bodies of
setup()
and draw()
so that you have three cars of different colors
traveling across the screen at different speeds. Write the program so that it saves an image
when the first car reaches the end of the screen named photo-finish.png
. Submit this image
along with your code.
Homework 3.3 - TBD
Homework 3.4 - Fraction Math
Last week, we covered some of the limitations of floating point numbers, but even if we aren’t working in binary, there are many rational numbers that cannot be represented in decimal notation either, such as 1/3.
In the starter project, a class called Fraction
has been provided with
stubs for various arithmetic operations. Write the bodies of these methods
so that they each return a new fraction with the correct value. The fractions
returned should be reduced to lowest terms.
For this assignment, you will need to consider some number theory concepts such as Greatest Common Denominator (GCD) and Least Common Multiple (LCM). The simplest way to find the GCD is with Euclid’s Algorithm written in pseudocode as follows.
function gcd(a, b)
while b ≠ 0
t := b
b := a mod b
a := t
return a
Homework 3.5 - Employee Directory
A goal of Object-Oriented Programming is to be able to model “Real World” concepts.
Many companies (and a university like Stevens) have Employee Directories. At their
simplest, an Employee Directory is a list of employees with their name and contact
information. The Employees are typically grouped into Departments. A Department
will have a Manager.
Describe how you would model an Employee Directory using Java objects. In writing your design, consider what objects you will need, what fields each object should have, and what methods. You do not have to write bodies for the methods as long as you describe what they should do, but your code should be written in valid Java that can be compiled.
Homework 4.1 - Checkers (or Something Like It)
Following the class example of making a button in Processing, write a Processing program to draw a chessboard / checkers board. These boards are typically drawn in black and white, but you can choose any combination of dark and light colors. When you click on a square, the program should draw a colored circle centerred in the square you clicked on (choose a different fill color for the circle from what you used for the dark and light squares).
Homework 4.2 - Planets of the Solar System
In the starter project for this project, you’ve been provided with a file called solarSystem.dat
,
which has information about the planets in our solar system in a table format,
and an class called Planet
with several fields corresponding to the columns in this table.
Complete the methods in the starter project to make the program open this file, read each line,
instantiate a Planet object with the right values from the file, and print out the planet’s
information to the command line (please use the Planet.print()
method for this);
Homework 4.3 - A Simple Spellchecker
There are over 200,000 words in the English language with more being invented all the time. For various historical reasons, English has many complicated spelling rules for writing many of these words. Modern spellcheckers like the one built into Micorosft Office use many language processing techniques to provide the user with useful suggestions.
A simple spellchecker, though, can be written by checking each word against a list of all known words.
Your task is to write a simple spellchecker in this way. For simplicity’s sake, your spellchecker will
not need to learn all 200,000+ words of the language. The starter project includes four text files:
words.txt
- a subset of the most common words in the language.peter-pan.txt
- a short passage from the the book Peter Panalice.txt
- a short passage from the the book Alice’s Adventures in Wonderlandoriginal.txt
- an empty file that you should fill in with some text of your own writing. Include some intentional misspellings.
Your task is to fill in the the method bodies in the starter project so that the program loads the words file and each of the sample texts and outputs the original text with each misspelling surrounded with two square brackets like this:
The [[qcuik]] brown fox jumped over the [[laazy]] dog
Homework 4.4 - The ROT-13 Cipher
ROT-13 is a letter substitution cipher related to the Caesar cipher. In the Caesar cipher, imagine that you had the letters of the alphabet written around the two circular disks. By rotating one of the disk, you arrive at a mapping from one letter to another. With the English 26-character alphabet, ROT-13 is the result of rotating the disk 180 degrees such that each letter of the first half of the alphabet maps to a letter in the second half and vice versa. The mapping looks like this:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
| | | | | | | | | | | | | | | | | | | | | | | | | |
N O P Q R S T U V W X Y Z A B C D E F G H I J K L M
Because the cipher is symmetrical, the original text can be recovered by applying the ROT-13 cipher to the encrypted text a second time.
Included in the starter project for this assignment is a file encrypted.txt
that contains a famous passage from a book encrypted using the ROT-13. Your task is to fill in the stub methods in the project to read in this file, decrypt it, and write the result to a file called decrypted.txt
.
Hint: remember from the first week’s homework, each character in Java is represented as a number encoded in unicode. Capital ‘A’ is the decimal number 65. Capital ‘N’ is the decimal number 78.
Homework 4.5 - TBD
Homework 5.1 - Lists of Integers
In week 1, you wrote a program to print out odd numbers, even numbers, and powers of two to the screen. For this assignment, you should use the same loops, but, instead of printing the results to the screen, each method should return a List<Integer>
containing the odds, evens, and powers of two respectively. You can print the lists to the console to check your work.
Homework 5.2 - Domain and Range
In math, we may talk about functions having a “Domain”, a “Codomain”, and a “Range”.:
- The Domain is the set of possible inputs to the function.
- The Codomain is the set of all possible outputs of the function
- The Range is the set of actual outputs the function produces
For example, in the continuous function \(y = x^2\), the Domain and Codomain are both the set of real numbers (ℝ) but the Range is restricted to the set of positive real numbers (+ℝ).
In week 2, we plotted some functions by creating lists of points such that \(\langle x, y \rangle = \langle x, f(x) \rangle\). In doing this, we were approximating these real-value functions as discrete functions.
In the starter project for this assignment, you are provided with a List<Integer>
containing the
integers -300 to +300 (the Domain). Using the four functions you graphed in assignment 2.2, create a List<Integer>
containing the output of each function for each element of the Domain and create a Set<Integer>
containing
the Range of the function. Output the minimum value, maximum value, and the size of each list and set.
For discussion purposes only, consider the circumstances underwhich the List and the Set have the same size and under which they have different.
Homework 5.3 - Bag of Words
Although computers tend to read passages of text one word at a time, it can be advantageous for computers to process text as a “Bag of Words”. A Bag of Words is a representation of the text as a table of the unique words in the text and the number of times the word appears in the text.
Using a Bag of Words the following text:
This is Spot. See Spot run. Run, Spot, Run.
Would be represented like this (ignoring capitalization for the time being):
this 1
is 1
spot 3
see 1
run 3
Create a Bag of Words from the sample text provided with the assignment. Use a Map<String, Integer>
to store the result. Note: in the version of Java we’re using there are many different ways to create this map. We will look at some of the newer ways to do this in a later week. For now, please limit your solution to only use the put()
and get()
methods of the Map
class.
Homework 5.4 - Text Summarization
NOTE 1: The solution to this assignment depends on the solution to homework 5.3, Please be sure that your solution to that assignment works before copying any code into your solution for this assignment.
NOTE 2: There are only four assignments this week instead of five because this assignment is a bit more involved than the ones for previous weeks. Please plan your time accordingly.
Part 1 - Cosine Similarity
Thinking back to geometry and linear algebra, a normalized vector quantity represents a direction. Two vectors can be said to be similar if the angle between the vectors is very small (If the angle is 0 degrees, they are equal, if the angle is 180 degrees they are exact opposites). It is possible to determine the angle between two vectors by using the Euclidean dot product formula.
\[ A \cdot B = \left||A\right|| \left||B\right|| \cos(\theta) \]
Therefore,
\[ \cos(\theta) = \frac{A \cdot B } {\left||A\right|| \left||B\right||}\]
We don’t really need the angle - using the cosine of the angle is good enough. A value of 1 means the two vectors are identical. A value of -1 means the vectors could not be more different.
Write a method to calculate the cosime similarity of two vectors
Part 2: Term Frequency Vectors
In homework 5.3, we constructed a Bag of Words (BoW) from a text package. Bag of Words representations
are used for many applications in natural language processing (NLP). We can take the BoW
and turn it to a vector (i.e. the type you’d find in linear algebra). So, for our example text,
This is Spot. See Spot run. Run, Spot, Run.
which had the following BoW representation:
this 1
is 1
spot 3
see 1
run 3
we might represent this as the vector [1, 1, 3, 1, 3]
, or, if we normalize the vector based on the
number of words in the original text [1/5, 1/5, 3/5, 1/5, 3/5] = [0.2, 0.2, 0.6, 0.2, 0.6]
.
Each element in the vector represents the frequency of a term in the original text. To know which term
each element represents, you would need to look back at our original table.
Now let’s say we wanted to compare our example text with another text: This is Jane. See Spot run to Jane.
, which would
have the following BoW:
this 1
is 1
jane 2
spot 1
see 1
run 1
to 1
We can make that a vector [1/7, 1/7, 2/7, 1/7, 1/7, 1/7, 1/7]
,
but we can’t do any operations on the pair vectors because they have different legnths. (Even if the vectors
were the same length, we really couldn’t do any meaningful operations on the vectors because the elements
map to different words. In the frist vector, the frequency of the word spot
is represented by the third
element, but in the second vector it’s represented by the fourth.)
So instead, we want to map both sentences to the same vector space including zeroes for words that appear in one sentence but not the other:
s1 s2
------------------
this 1 1
is 1 1
jane 0 2
spot 3 1
see 1 1
run 3 1
Or with normalizing (each sentence is still normalized using only the number of words in the original sentences, not the total number of words)
s1 s2
--------------------------
this 0.2 0.14285...
is 0.2 0.14285...
jane 0.0 0.28571...
spot 0.6 0.14285...
see 0.2 0.14285...
run 0.6 0.14285...
to 0.0 0.14285...
Given a list of sentences, create the normalized term frequency vectors for each sentence using the combined vocabulary as shown in the example above.
Part 3 - Inverse Document Frequency
When searching for something, you generally want to focus on the characteristics that makes it unique. If you’re looking
for a book on your shelf, your first thought probably isn’t “It has white pages”. Likewise, in English, if you try to
find all the sentences in this homework that contain the word “the”, you might as well just look at every sentence.
The Inverse Document Frequency is a statistical measure used to represent how important or unique a word is. The formula is:
\[ IDF(t) = \log \frac{N}{df_t} \]
Where \(N\) is the total number of documents and \(df_t\) is the number of documents that contain the term \(t\). Note that for our purposes, a “document” is actually a sentence.
Similar to term frequency, we can createa a vector of IDF values for each word.
IDF
--------------------------
this 0.0
is 0.0
jane 0.30102...
spot 0.0
see 0.0
run 0.0
“Jane” is the only word with a positive value, because it is the only word that is in one sentence but not the other.
The third part of the assignment is, given a list of sentences, create the IDF vector for the combined list of words in each sentence.
Part 4 - Text Summarization
We’re all busy. Who has time to read anymore? Imagine if you could take a long article and automatically identify only the most important sentences in the article. While there are certainly ways to create something a bit like that. We are going to make a simple summarizer by combining the work we did in Parts 1, 2, and 3.
A term frequency–inverse document frequency (TF-IDF) vector is made by multiplying (Hadamard / element-wise product) the TF vector from Part 1
with the IDF vector in Part 2. This is another metric on how important each word is to the source text.
A rare word (high IDF) that appears multiple times (high TF) is more important than a common word (low IDF) that appears few times (low TF).
By feeding two TF-IDF vectors into the Cosine Similarity function from Part 1, we can generate a scalar value representing how similar the
two sentences are.
So one way to summarize the long text is to eliminate as much repetition as possible. We want to select the sentences that have the most overlap with other sentences in the article.
For each sentence in the longer text, calculate the TF-IDF vector for the sentence and then calculate the cosine similarity between that sentence’s vector and every other sentence’s vector. Finally, select the sentences that have the highest average similarity measure.
One more note: English is a messy language. In the sample text, I spent some time cleaning it by manually breaking up each sentence into lines. I also added a pre-process step that you don’t need to implement that filters out certain extremely common words before any of your processing code will run.
Homework 6.1 - TBD
Homework 6.2 - Nutrition Fact Builder
In the started project, you have been provided with a class called NutritionFacts
. Every field in this class is optional but final,
meaning they must be set in the constructor if at all. We could create multiple constructors, but with so many properties,
the number of constructors you would need to write grows exponentially.
Using the Builder Pattern discussed in class to write a NutritionFactBuilder
class that will create an instance of the NutritionFacts
class.
Homework 6.3 - Equals and Hash Code
A point in 3D space can be represented by Cartesian coordinates (x,y,z). The same point can also be specified in Cylindrical coordinates (r,θ,z). You can check if two points in Cartesian space are equal by checking that each component matches. You can do the same for two points in Cylindrical coordinates. In order to compare a point in Cartesian coordinates to a point in Cylindrical coordinates, you will need to do some conversion.
In the starter project, three classes are defined abstract Point3D
and two subclasses CartesianPoint
and CylindricalPoint
. Implement equals
and hashCode
in both subclasses so that it is possible to test equality of points in both systems against each other. The equations for converting
between Cartesian and Cylindrical coordinates are:
\[ x = r \cos \theta \]
\[ y = r \sin \theta \]
\[ z = z \]
Remember, the Java trigonometric functions use the double
type which means you will need to account for possible rounding errors when checking equality.
Remember also, the Java library expects hashCode
to behave like this:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Homework 6.4 - Comparing Apples to Apples
Several incomplete classes are provided in the starter project that each implement the Comparable
interface. Write the body of the compareTo
method for each of these classes such that it behaves as follows:
- An
AppleBasket
should be sorted by the number of apples it contains. - A
Person
should be sorted alphabetically by last name and then first name ascending. - A
BirthdayReminder
should be sorted chronologically by date. - A
3DPoint
shoud be sorted by distance from the origin.
Homework 6.5 - Enums that Behave Themselves
Enums in Java are typically used to represent a set of related constants in a type-safe way. For example, you might have something like
enum DayOfWeek{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
But, as we saw in class, Java enums are more than just fancy variables. They are full classes and can have behavior. Create an named Operation
with four values: ADD
, SUBTRACT
, MULTIPLY
, DIVIDE
. Each one should have a property called symbol set to +
, -
, ⨉
, and ÷
respectively and should implement the method int apply(int a, int b)
appropriately for the given operation. The enum should also include a method public Operation fromSymbol(char symbol)
that returns the appropriate enum value.
Homework 7.0 - Midterm Exam
The midterm exam takes place this week. There will be no additional homework assignments.
Homework 8.0 - Spring Recess
Spring Recess - no assignments this week, but you should begin thinking about your final project.
Homework 9.1 - Maven Dependencies
The directory structure of this week’s assignments is a bit different than you’re used to. They are now structured according
to the conventions expected by the Maven build tool. You will find the .java.
files in src/main/java
(or src\main\java
if you’re on Windows). The project is configured based on the pom.xml
at the top of the project folder.
You can run this project in the command line with this command:
mvn compile exec:java
BUT if you try that right now, you will get an error. That’s because this project has a missing dependency to Apache PDF Box. To make it run,
add a dependency to version 2.0.21
of the library.
Once you add the dependency, running the command above again should produce an empty PDF file. In Main.java
there is some code commented out.
Uncomment this code and modify it so that it prints your name in the PDF.
Submit your PDF along with your updated code.
Homework 9.2 - TBD
Homework 9.3 - TBD
Homework 9.4 - TBD
Homework 9.5 - TBD
Homework 10.1 - TBD
Homework 10.2 - TBD
Homework 10.3 - TBD
Homework 10.4 - TBD
Homework 10.5 - TBD
Homework 11.1 - Stock Prices API
Many software companies and some hobbyists provide web APIs (application programming interface) that allow us to interact with their software by making network requests. For this assignment, we will be using the FinHub API which is available for free subject to certain usage limits. With the free tier we’ll be using, you will only be able up to 30 API requests per second. Sign-up to receive a free API from https://finhub.io
IMPORTANT: When you sign up for an account you will get what’s called an API key to make your requests. You should NOT add this key to your GitHub submission. See the comments for the sample code for more information on how to protect this key.
Your goal is to write a project to retrieve stock quotes. The user will be presented with a command prompt where they can input a stock symbol. The program should then make a request to the Finhub API and present the user with the latest information for that stock.
The API request you are going to use is https://finnhub.io/api/v1/quote?symbol=<symbol>&token=<api_key>
It will give you five attributes back. They use very short names to identify everything to save on network traffic. When you display the information to your user, you should use longer, more descriptive labels:
- o - Open price of the day
- h - High price of the day
- l - Low price of the day
- c - Current price
- pc - Previous close price
Homework 11.2 - Animal Collage
There are a number of novelty websites that will provide random images of animals. Some of them will additionally let you specify the dimensions of the image you request in pixels. Use any combination of the following APIs to make a collage of randomized animal pictures:
- https://placegoat.com
- https://placekitten.com/
- https://placedog.net/
- https://placebear.com/
You can use Processing from within Java to complete the layout. Recall how we did this in Homework 6.1. You will need to do this in a two-step process: first make requests to download your images and save them. Then execute execute the processing program and save your final image to a file. Save you final collage and submit it with your source code.
Homework 11.3 - TBD
Homework 11.4 - TBD
Homework 11.5 - TBD
Homework 12.1 - Counting in Streams
As discussed in class, Streams are an alternative way to handle iteration in Java in a Functional programming style. Write a Java program that use streams to create the following lists and print them to the screen. A starting point will be provided to you in GitHub. Please read the comments in the GitHub files.
Print out the even numbers from 2 to 100 (inclusive).
Print out odd numbers from 1 to 99 (inclusive).
Print out the powers of 2 from 1 to 4096.
Homework 12.2 - TBD
Homework 12.3 - TBD
Homework 12.4 - The Strategy Pattern with Lambdas
In assignment 6.5, we created an Operator enum and used method overriding to implement each operator. Now, lambdas
give us another way to express the same behavior. Create a new version of the Operator
enum that has the same behavior
but instead of using a method override, give each instance of the enum a property called operation
of type BiFunction<Integer, Integer, Integer>
that is initialized in the constructor of each enum instance. Write labmda functions to implement the four basic arithmetic operations.
Homework 12.5 - TBD
Homework 13.1 - Simple Calculator
In the starter project, a screen for a simple calculator has already been created for you. Each button is connected to a handler method. You can look at the calculator.fxml
file to see which methods handle which buttons. Your job is to make the calculator work for basic arithmetic.
The simplest calculator uses three registers:
- The current number being displayed
- The current operation being performed
- The previous number in memory
When you hit a number key, the screen is updated. When you hit an operator, the displayed number is moved to memory, the display is cleared, and the current operator is set. When the equals button is pressed, the operator is applied to the previous number in memory and the current number on the screen and the screen is updated with the result.
Create some fields in the CalculatorController
class to represent these concepts. For the operator, you may want
to reuse the Operator enum you made in a previous assignment. Then implement the button handler methods accordingly.
Homework 13.2 - Simple Text Editor
The skeleton of a simple text editor is provided using JavaFX. Recall the various file interaction methods from week 4. Implement the button handlers for the following toolbar actions:
- New- creates a new blank file
- Open - opens a file browser to select a file and loads the selected file into the editor pane
- Save As - opens a file browser and saves the current content of the editor pane to the new file in the location chosen in the browser
- Save - replaces the contents of the currently open file with the contents of the editor. This option should be disabled for a new file that has not yet been saved using Save As
JavaFX provides a built-in file chooser that you should use. You can read the documentation for it here: https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html
Homework 13.3 - TBD
Homework 13.4 - Multi-Threaded Hello World
Write a short program that prints “Hello world” from a thread.
Once you have it working, modify the program to print “Hello world” five times, once from each of five different threads.
Finally, modify the printed string to include the thread number; ensure that all threads have a unique thread number.
Homework 13.5 - Producers / Consumers
Write a program that creates two threads. In one thread is a Producer that generates numbers sequentially counting by fives that places a number into a queue once per second. The queue can only hold 10 items.
In the other thread is a Consumer that reads two numbers from the queue every five seconds. It should print the two numbers retrieved from the queue to the screen.