ICS4U Java BOOKLET 1 - Data Structures
ICS4U Java BOOKLET 1 - Data Structures
https://www.oracle.com/technetwork/java/javase/downloads/index.html
Windows: https://www.jetbrains.com/idea/download/#section=windows
MAC: https://www.jetbrains.com/idea/download/#section=mac
Now you will see this in your coding window on the right:
1
ICS4U - Java
Add the following two inside the class. Every new file you make will need to have a main function.
You should see the words Hello, World! In the output dialog box at the bottom of the screen.
Shortcut: you can type “sout” and then hit the “tab” key to shortcut to System.out.println()
*** to avoid typing the main method every time, similarly use “psvm” with tab to get the signature
2
ICS4U - Java
2. Terms in Java
System.out.println("Hello World");
Define the following terms: For each term, link to an example in the code above
a. Keyword: Words belonging to a programming language which are used for various operations
(i.e. class, public, static, void)
b. Comments: Documentation within classes designed to clarify the purpose of certain portions of
code. Can be one line ‘//’ or can be /*…….*/ multiple lines.
c. White space: Any sequence of only space, tab, and newline characters. These characters affect
formatting/appearance of the code, but (unlike with Python) have no impact on how the code
runs.
d. Class: The basic building block of Java. For the purposes of this course, each Java file we
produce, represents a Class.
e. Method: Blocks of code that can carry out a specific task multiple times. A Class can be made up
of multiple methods.
3
ICS4U - Java
3. Output in Java
For each of the following lines of code:
3. Write the results of actually running the code. If the code does not run, indicate “Syntax Error”
*after testing each line, comment it (//) so it no longer runs
l.) System.out.println(6%3);
m. System.out.println(7%3);
)
n.) System.out.println(8%3);
o.) System.out.println(9%3);
4
ICS4U - Java
5
ICS4U - Java
In Python, you don’t have to state in advance the variable type. Python will infer it from the value you
give it. In Java, you must tell it what the variable type will be (this is one way that Java has to do less
“figuring out” and therefore runs faster than Python, but it requires more coding).
Those data types have keywords in java: int, float, double, char, and String (capital S)
Python Java
age = 18 int age = 18; // needs a ;
pi = 3.1415 float pi = 3.1415;
likesBurgers = True # upper case True Boolean likesBurgers = true; // lower case true
Make a new Java Class and call it “Lesson2Variables”. Type in this code (without comments) and run.
6
ICS4U - Java
Exercise:
a) Write a program that declares a variable for each of the main data types and outputs them to
the screen.
Naming Variables: variables in Java have to start with a lower case letter. They can have numbers after
the first letter, but no special symbols anywhere. Variables with multiple words can have an underscore
between then, first_name, or have every new word start with a capital, firstName.
Acceptable: No good:
5: Basic Math
You can perform the same operations as Python (+, -, *, /). Type in and run the following:
public class tryingmath {
public static void main(String[] args) {
double x = 5;
double y = 7;
double z = x/y;
System.out.println("Quotient: "+ z);
z = x*y;
System.out.println("Product: "+ z);
z = Math.pow(x,y);
System.out.println("Power: "+ z);
}
}
You can’t use ** as an exponent like you can in Python (e.g. 5**2). But you can use the function:
z = Math.pow(x,y);
7
ICS4U - Java
Exercises:
1) Write a program that declares two double variables. You can pick any numbers for them
between 10 and 20. The program should:
Add them, subtract, multiply, divide, raise one to the power of the other and vice versa. It
should store the results in four new variables. Output them to the screen in a nice-looking
way.
2) Write a program that stores the radius of a circle in an appropriate variable and give it some
value, for example, double radius = 5.5.
a. Calculate the circumference (and store it in a variable called “circumference”). You
can make another variable to help:
3) Similar to question (2), write a program that calculates the perimeter and area of a
rectangle. You can start with variables length and width and give them values. Output the
perimeter and area in a similar way.
4) Write a program that solves the Pythagorean theorem. Start with two doubles, called a and
b. Give them values. Calculate the hypotenuse, store it in double c, and output it in a nice
way (see below). You can use Math.sqrt() method to do this.
5) Write a program that calculates and outputs the surface area and volume of a cone, give
the height and radius (these values can be hard coded into variables like you did in previous
questions). You may have to look up the formulas.
8
ICS4U - Java
Data Casting
Block comment out your previous programs. Now add these lines to your main method, and see the
new output:
int a = 3;
int b = 4;
double c = a/b;
System.out.println(a + " / " + b + " = " + c);
You’ll notice it gives you an answer of 0.0 instead of 0.75. When you divide integers, the result is an
integer. You can store it in a double data type but it has already lost its decimals. To avoid this, change
the line to:
double c = (double)a/(double)b;
This is called “casting” the variable’s value to be a type double (casting = changing the data type). You
can do this between numerical values, but not between numbers and Strings / chars.
If you are casting values directly, not variables that store values, you can add a “d” after the number to
make it a double, or “f” to make it a float, for example, try these:
Casting Exercises:
1) Declare two variables as integers and give them integer values. Divide them while casting them
as doubles, and store the result in a new double. Output the result.
2) Declare two variables as doubles and give them decimal values. Divide them and cast the result
as an integer. Output the result.
9
ICS4U - Java
Java has a few other primitive data types (primitive = basic and easy to handle). String is not actually a
primitive data type. It is a class (more on that later).
You can save memory by using a byte data type if you only need to store small numbers that go up to 2 8
= 128.
If you need to store an integer value greater than 2 32 = 4.295 x 109 (4.2 billion), you would need to use a
long data type.
Variables in Java actually store a memory address in RAM. At that memory address is the value the
variable is holding. When you run this line: int x = 3;
Java creates a location in RAM (a memory address) that is 4 bytes in size to hold the number you are
placing there.
10
ICS4U - Java
// or a double...
double num2 = scan.nextDouble();
System.out.println(num2 + " squared is " + num2*num2);
}
}
Use different functions to take in different data types (nextLine for Strings, nextInt, nextFloat,
nextDouble, etc.)
*** whenever you take in a new data type with scanner, it must be reset:
scan = new Scanner(System.in);
11
ICS4U - Java
Exercises:
a) Write a program that asks for a person’s favorite food (String) and outputs it back to them
b) Write a program that asks for two numbers (int). It should multiply them together and print the
result
c) Add to (b) by making the program calculate the first number to the power of the second like we
did in program 3, and output the result (doubles)
d) Write a program that asks the user for the radius of a sphere, and outputs surface area and
volume.
e) Create a Pythagorean theorem program that asks for sides A and B, then calculates and outputs
the hypotenuse.
12
ICS4U - Java
This is called explicit casting (you are stating out in the open the data type you want). This is usually
done to get an answer with more precision than the original data types being used.
Implicit Casting:
Sometimes you don’t need to be explicit. For example, you *can* do this:
byte a = 15;
int b = a;
Exercise: between byte, short, int and long, test which pairs of data types can be implicitly casted and
which can’t. After experimenting, come up with a rule.
Numbers to Strings:
You can’t cast numerical values to symbolic ones (e.g. int to String). There are built-in functions that do
this. Try these:
// integer to string
int a = 15;
String s = Integer.toString(a);
System.out.println("your integer is " + s);
// float/double to string
float pi = 3.14f;
String sp = Float.toString(pi);
There’s also a really easy way to do it, just by adding “” symbols before the numeric variable:
int n = 3;
String s = ""+n;
13
ICS4U - Java
Strings to numbers:
Converting strings of numbers into numerical data types is called parsing. The functions have that word
in them:
// String to float
String pi = "3.1415";
float float_pi = Float.parseFloat(pi);
// String to int
String s = "5";
int int_s = Integer.parseInt(s);
Exercises:
String pi = "3.1415";
int int_pi = Integer.parseInt(pi);
b) Write a program that uses scanner to input two integers from the user. Cast both integers to
Strings, combine them, and output the result. Sample output:
c) Write a program that scans in two strings from the user (in integer format). Cast both strings to
integers, add them, and output the result.
14
ICS4U - Java
In Java String is not a Primitive Data Type. It is an entire class with many functions/methods. .length() is
a very useful method.
Here are some String class methods: try each of these in order to see the output
String s1 = "hello world";
// .length() - getting the length of a string and returns int
System.out.println(s1 + " is " + s1.length() + " characters long");
// .indexOf(char c) - returns the location index of the first time that char appears
System.out.println("x occurs at location: " + s1.indexOf("x")); // -1 not in the string
System.out.println("l occurs at location: " + s1.indexOf("l"));
// .substring(int n1, int n2) - gets the substring between n1 (includes) and n2 (doesnt
include)
System.out.println("first 4 letters: " + s1.substring(0, 4));
System.out.println("last 4 letters: " + s1.substring(s1.length()-4, s1.length()));
15
ICS4U - Java
Exercises:
1) Write a program that asks the user to input a string of 2 words with first letters capitalized. For
example: “Hello World!”
2) Perimeter of a rectangle: ask the user for the length and width of a rectangle separate by a
space, for example: “5.6 8.62”. Separate their input into two strings stored in new variables.
Parse the Strings into double in two new variables. Calculate and output the area and perimeter
of the rectangle.
3) Pythagorean theorem: ask the user for sides A and B separated by a space. Parse them to
doubles, then calculate and output the hypotenuse.
4) Ask the user the input a 9 digit integer and take it as a String, for example “111222333”.
a. Save the first 3, middle 3, and last 3 numbers in new Strings.
b. Combine and output the first 3 and last 3, e.g. “111333”
c. Parse all three Strings into integer. Add them all together and output the sum.
16
ICS4U - Java
Sample code for generating a random numbers: try these and any variations in a new class file.
// between 0 and 1
double num1 = Math.random();
System.out.println("a number between 0 and 1 is: " + num1);
System.out.println("formatted to 2 decimals: " + String.format("%.2f", num1));
// 0 - 10
double num2 = Math.random()*10;
System.out.println("0 - 10, 3 decimals: " + String.format("%.3f", num2));
// 1 - 6
double num3 = 1 + Math.random()*5; // 1-6
System.out.println("a number between 1 and 6 is: " + num3);
17
ICS4U - Java
}
}
Exercises:
1) Write a program that asks the user to input decimal number, using scan.nextDouble(). Then
output:
a. the original number, and the number formatted to 4 decimal places
b. the cube of the number
c. a random number between 0.0 and the number
d. rounds the number to the nearest integer
√( ) ( )
4
3 3 2
b. + - cube root, same as an exponent of 1.0/3.0 – using Math.pow()
4 5
3) Ask the user to input 2 numbers. The program should take the lower number (using Math.min)
and output the absolute value of that number plus 10. For example, if the user inputs 3 and -5,
the program will output abs(-5 + 10) = 5.
double x = 2.5;
double y = -1.5;
int m = 18;
int n = 4;
String s = "Hello";
String t = "World";
Determine what the output would be for the following without coding it:
line output
1 System.out.println(x + n*y - (x + n)*y);
2 System.out.println(m/n + m%n);
3 System.out.println(5*x - n/5);
4 System.out.println(Math.sqrt(Math.sqrt(n)));
5 System.out.println( (int)Math.round(x));
6 System.out.println((int)Math.round(x) + (int)Math.round(y));
7 System.out.println(s + t);
8 System.out.println(s + n);
9 System.out.println(1-(1-(1-(1-(1-n)))));
18
ICS4U - Java
10 System.out.println(s.substring(1,3));
11 System.out.println(s.length() + t.length());
Like Python, Java comparisons can either be true or false. Give the Boolean value for the following:
Say that a and b are Boolean expressions that can be true or false.
AND – both must be true OR – only one needs to be true XOR – only one can be true
a b c = a && b a b c = a || b a b c = a^b
false false false false false false false false false
true false False true false true true false true
false true false false true true false true true
true true true true true true true true false
Exercises:
1) Complete the truth table:
19
ICS4U - Java
3) Try each of these examples in Java. One will compile, but the others will not.
// example A
int x = 0;
System.out.println(50/x);
// example B
int x = 0;
System.out.println(x==0 || 50/x>2);
// example C
int x = 0;
System.out.println(x==0 && 50/x>2);
20
ICS4U - Java
Python:
grade = 75
if grade >= 80:
print("you made the honour roll!")
elif grade >= 50:
print("you passed")
else:
print("you failed")
Java:
double grade = 75;
if (grade >= 80){ // Boolean expressions go in brackets ()
System.out.println("you made the honour roll!");
} else if (grade >= 50){
System.out.println("you passed");
} else {
System.out.println("you failed");
}
Exercises:
1) Write a program that asks the user to input a number. It should output a different statement
depending on the number of digits of the number:
digits Output
1 “less than 10”
2 “double digits!”
3 “hundreds”
4 “thousands”
>4 “that’s just big!”
2) This program generates a random “grade” between 40 and 100. It should output the
appropriate letter grade for the mark (e.g. > 90 is A+, > 80 is A, > 70 is B, etc.)
3) Ask a user for the length and width of a rectangle. It should calculate the perimeter and output
it. If the perimeter is greater than 100, output, “too large”, if it is less than 50, output “too
small”. If it is between 50 and 100, output “good choice”.
21
ICS4U - Java
Switch Statement: this is a shorthand that lets you do multiple if statements to compare a variable to
multiple set values. It only works for the == operator. You can’t do it for > or <.
String food = "grapes";
switch (food) {
case "orange":
System.out.println("bad for your teeth!");
break;
case "apples":
System.out.println("keeps the doctor away");
break;
case "grapes":
System.out.println("yum!");
break;
default: // any other options
System.out.println("that food is not in the list");
}
You can give multiple values the same outcome:
String food = "plum";
switch (food) {
case "plum":
case "apple":
case "orange":
System.out.println("this will print for the 3 above fruits");
break;
}
You can also write it with arrows, and not have to include the terms case or break;
String day = "M";
switch (day) {
case "M", "T", "W", "R", "F" -> System.out.println("weekday");
case "Sa", "Su" -> System.out.println("weekend");
default -> System.out.println("that is not a day");
}
Exercises:
1) Use a switch: write a program that asks the user for a letter grade, e.g. “A”, “b”, etc. It should be
able to handle upper or lower case (you can use a string operation). Output the grade range for
that letter. For example, if they enter “C”, output”
60 – 60 %
22
ICS4U - Java
2) Use a switch: write a dice rolling / craps program. It should roll two random dice (integers
between 1 and 6). Output:
“winner!” if they add up to 7 or 11
“not bad!” if they add up to 6
“snake eyes!” if they add up to 2
3) Modify your die rolling game. Don’t use a switch, just use if statements with && and ||
a. 7 or 11: “winner!”
b. 6: “not bad!”
c. 2: “snake eyes!”
d. If you roll the same number on each: “doubles!”
e. If both rolls are 1-3: “under 4s!”
f. If both rolls are 4-6: “over 3s!”
g. If one roll is 1-3 and the other is 4-6: “over under!” (note: there are two ways this can
happen. Have them both in a single if statement with and and ors)
h. If both rolls are even: “evens!” (use modulus, example below)
int x = 4;
if (x % 2 == 0){
System.out.println("even!");
}
j. If one roll is even and the other is odd: “even/odds!” (two ways for this to happen as
well)
4) For each situation below, code an appropriate solution using either (a) if, (b) if else (c) if else-if
or (d) if else-if else
a) Use a person’s age (int age) to determine whether they are eligible to vote – if they are 18 or
over. Output a message “you are eligible” or “you are not eligible”
b) Use a person’s age and whether they have job experience (yes or no) to see if they are suitable
for a job. In order to be suitable they should be over 16 and have experience. If they are
suitable, output “suitable”, otherwise output a message for reasons why they are not, e.g. “not
16” or “no job experience” or “not 16 and no job experience”
c) Generate a random number and ask the user to enter a number.
a. If the user input is lower, indicate whether it is less than half, half, or more than half the
random number
b. If the user input is equal, output “equal”
c. Otherwise output “greater”
23
ICS4U - Java
24
ICS4U - Java
// METHODS
// main
public void main(String[] args){
// main program goes here
}
Exercise: add these programming conventions to your previous die-rolling program, and use it in all
future programs.
25
ICS4U - Java
Exercises:
a) Make a program that asks the user to input a min and max number. Your program should output
all the integers between those two numbers
b) Change (a) to output every other number (by adding 2 each time)
c) Output all multiples of 5, but in reverse, so it will count down from 100.
With a Boolean
This while loop uses a Boolean to keep looping until the user is ready to quit:
import java.util.Scanner;
26
ICS4U - Java
Exercises:
a) Make a program that takes a double as input from the user. Then a while loop should ask them
to enter “1”, “2” or “3”.
1: the loop doubles the number and outputs the result
2: the loop halves the number and outputs the result
3: the loop exits
b) Make a program that asks a user for a positive integer (-1 to quit). After the number is received,
the program must display how many numbers have been received (what “round” it is, basically)
and output the total sum of the numbers so far. The program will exit when any negative integer
is input.
c) Write a program that has users input positive integers. Every time an integer is input that is
evenly divisible by the previous input integer, the program should output a message like:
d) Make a “war” game inside a while loop. Every loop, a random number between 1 and 10 is
generated for the user and computer. Whoever has the higher card gets a point (if it’s a tie no
one gets a point). You can keep playing while the user hits enter, and exit when they input “q”
to quit. Give it appropriate output messages for each hand, for example:
27
ICS4U - Java
If you program your while loop correctly, you should always be able to exit the loop. There is a way to
force break out of a loop using a break. Here’s an example that uses a break and no Boolean variable.
import java.util.Scanner;
}
}
Exercises:
a) Rewrite program (a) from above using while (true) and a break
b) Rewrite program (b) from above using while (true) and a break
*** There are some cases where a break is necessary, but generally speaking, I would prefer you to use
other methods as it’s a bit lazy.
28
ICS4U - Java
}
}
*** you can also use floats or doubles as your counters in for loops. It’s less
common, though.
Exercises:
a) Make a program that asks the user to input a min and max number. Your program should output
all the integers between those two numbers
b) Change (a) to output every other number (by adding 2 each time)
c) Output all multiples of 5 from 100 down to 5 in reverse order: 100, 95, 90…
d) Write a program that asks the user for an integer. It should output all the factors (integer
divisors) of that number. At the end it should output the total number of divisors. Use modulus.
e) Make a program that “deals” a user hand – it uses a for loop to generate 5 random numbers
from 1-10. It should add them up to a total. Do the same for the computer hand (you can do this
in the same FOR loop). Whoever has the higher hand wins – output a message comparing the
scores and declaring the winner after the loop
f) Add to (e) put the whole thing inside a while loop with Boolean condition so the user can keep
hitting enter to play another round, or “q” to quit.
g) The Fibonacci sequence is a sequence where each term is the sum of the previous two terms:
1, 1, 2, 3, 5, 8, 13, 21, …
Write a program that outputs the Fibonacci sequence. It should ask the user how many terms to
output. For example if the user enters “10” it outputs the first 10 terms.
29
ICS4U - Java
In each problem: the user enters a string, which I will call userWord, consisting of lower case letters
only. You can use to help:
userWord.toLowerCase());
Consider the number (ASCII) values of characters: “a” = 97, “b” = 98, “c” = 99, …, “z” = 122
You can get the letter value by casting as an integer:
Exercises:
Output all the letters of the word and their values (I will help with this one)
Sample output:
30
ICS4U - Java
16: Arrays
Arrays are like lists in Python but you initialize/declare them entirely different. In Python, we used lists
and appended to them, for example:
Method 2: start them empty and give them values later (more common)
int x[] = new int[10];
String words[] = new String[10];
double dubs[] = new double[10];
*** these three arrays are EMPTY. You can’t access their values. You have created space in memory to
hold those data types.
import java.util.Scanner;
class Scratch {
// input a value to it
System.out.println("Enter second number: ");
x[1] = scan.nextInt();
31
ICS4U - Java
}
}
Exercises:
a) Declare an integer array of 5 numbers (you can just make up numbers to put in). Use a for loop
to output them.
b) Declare a string array of five of your favorite foods. Use a for loop to output them in a nice way.
c) Declare an empty double array of 5 values. Use a for loop to store random values between 3 and
7 in each. Also output them.
d) Declare an empty array of 10 integers. Use a for loop to store and output the perfect squares of
1-10 in them.
e) Declare an empty array of 10 integers. Use a for loop to store successive multiples of 2. (e.g. 0,
2, 4, 6, etc.)
f) Repeat (e) but the user can input the size of the array and the multiple.
g) Add to program (f): use a for loop to add up all the numbers in the array and then output the
sum
Assessments:
a) Create a program that uses a loop for the user to keep inputting test scores. Put those scores
into an array. Since you don’t know how big it will, create a 10 integer array and populate it with
zeroes to start. When the user enters a negative value, the loop exits. Calculate the average of
the scores in the list and output them.
b) Speed dial:
a. Make a list of ten 7-digit phone numbers. Use a for loop to randomly generate the
numbers e.g. nums[i] = (int)(Math.random()*9999999);
b. Make a second list of 10 names (Strings). You can simply make up names.
c. In a while loop, ask the user for a number, 0-9, and outputs the name and phone
number of that item in the list. Otherwise, you can use -1 to quit.
c) Modify program (a). The user should be prompted to modify a value, for example:
32
ICS4U - Java
d) Write a program that simulates rolling 2 dice 100 times. It should count how many times each
roll occurs and store those totals in a list, which you can output at the end.
33
ICS4U - Java
17: ArrayLists
Arrays are limited in functionality because you need to predetermine the size when you first declare
them. Their size is not dynamic (this has never caused Mr. Craig any problems in his program – you just
have to be aware of the maximum size they can get and set that as their start size).
ArrayLists are dynamic, which means they can be resized, and they function just like lists in python, with
functions similar to append() and remove().
This code shows how you can create an ArrayList, add to it with .add() and retrieve from it with .get()
//The type of data held by the ArrayList should be typed in the <>
ArrayList<String> stringsList= new ArrayList<>();
for(int i=0;i<stringsList.size();i++){
//Data from location i in the list can be retrieved with .get(i)
System.out.println(stringsList.get(i));
}
Things to note:
1) You will need to import: import java.util.ArrayList;
2) ArrayLists don’t hold primitive data types (boolean, int, char, double). They instead use whats
called a “wrapper class” which lets you treat primitive data types as objects. This allows you to
easily use built in methods for them in your programs (more on this later). For now, just know
that the wrapper class just uses a capital first letter and full word:
int Integer
boolean Boolean
char Character
double Double
34
ICS4U - Java
Exercises:
f) Redo the test average program with an ArrayList to store each score. The user inputs test scores
until they enter (“q” or -1) and then it outputs the average.
35
ICS4U - Java
1) Addition: you have to add two numbers by hand (old school way). Let’s say a single digit addition
like 3 + 4 = 7 counts as “one addition”. How many additions are required for the following?
1x1= 1x2=
2x1= 2x2=
3) A computer program generates a random number between 1 – 100. You have to guess and the
program will say “higher” or “lower” until you guess the number.
a) Suggest the least efficient algorithm you can think of to accomplish this.
a. How many guesses could it take in the worst case scenario?
b. If you double the max number 1 – 200, how many guesses could it take in the worst
case scenario?
36
ICS4U - Java
The most important part of a computer program is that it works. The second most important
consideration is how efficient the code runs and Big-O notation is a way of describing the relative
complexity / computational use of your programs. Better algorithms will still run quickly when the data
sets become very large. Bad algorithms will hit a computational wall when data sets become very large.
Examples:
O(1): constant
Regardless of how big your data set is, the computational cost is constant.
Example:
Explanation: the size of array x[] has no impact on how long this takes. x[] could be 10
items or 1, 000, 000 items long. It still takes the same amount of time to print the 5 th
item.
O(n): linear
The cost increases linearly with your data set size (e.g. if the data set is twice the size, the
algorithm takes twice as long.
Examples:
The first addition example on the last page is O(n). If you had n digit numbers, it takes n
additions of individual digits.
Since list (b) is twice as long, the for loop must iterate twice as many times. If the array
is n items long, the loop will iterate n times. This is O(n)
37
ICS4U - Java
O(n2): quadratic
As the data set grows, the cost increases as the square of the growth.
Example:
1) Everyday Multiplication:
2x3 1 operation (2 x 3)
21 x 31 4 operations (1 x 2, 1 x 2, 3 x 2, 3 x 1)
211 x 311 9 operations
2) Example 2 from the first page: nested for loops: outputting a multiplication tables:
int numberOfCalcs = 0;
for (int i = 1; i <= 10; i++){
for (int j = 1; j <= 10; j++){
System.out.println(i + " x " + j + " = " + i*j);
numberOfCalcs ++;
}
}
This code outputs every multiplication from 1 x 1 to 10 x 10. Integer i first takes a value of 1, and
j takes values 1 through 10. Then i takes value 2 and the process repeats. There are clearly 10 x
10 (102) calculations here. The variable numberOfCalcs will be 100. If we increase i and j to a
maximum of 20, then there will be 20 2 = 400 calculations.
A nested for loop (a for loop in a for loop) is O(n 2). Likewise, if you had a third nested for loop, it
would be O(n3)
Example:
The third example on the first page: higher/lower number guessing game. Every
computation divides the data in half.
Algorithms that use recursion can be exponential. We will study this later in the course.
38
ICS4U - Java
This graph helps you visualize Big O notation for algorithms. You can see that O(n 2) the computation
time increases much more drastically for larger data sets.
39
ICS4U - Java
Rule: You focus on the most complex part of the program and assume the worst case scenario.
Example: looking up a name in the phone book to get the phone number. You can do this in many ways:
1) Start from page 1 and keep flipping pages until you get there.
2) Keep bisecting the telephone book. First cut it in half at a-h / h-z. Then cut those halves in half,
etc.
Worst case: keep dividing by 2 and its on the very last page O(log n)
General Rules:
- A single computation:
- A for loop that runs a set number of times regardless of data set size (e.g. always doing
something 3 times):
- A for loop that runs n times, for example, goes through an array of length n:
- A for loop that runs n times followed by another for loop that runs n times:
- A for loop that runs n times inside another for loop that runs n times:
- A for loop that runs n times inside another for loop that runs m times:
- A process that splits the data you need to look at in half every iteration:
40
ICS4U - Java
Practice: With a partner determine the Big O complexity of the following blocks of code:
41
ICS4U - Java
42
ICS4U - Java
class Scratch {
If you input anything other than an integer your program will crash with:
Try-Catch Blocks
To deal with this, anytime you take in input from the user that may be inappropriate, you have to use a
try-catch block.
try {
// the line that might crash
} catch (InputMismatchException e) {
// what to do if crash (error message)
}
class Scratch {
}
}
43
ICS4U - Java
import java.util.InputMismatchException;
import java.util.Scanner;
class trycatchexample {
while (true) {
System.out.println("Enter a number: ");
try {
num = scan.nextInt();
break; // if it works
} catch (InputMismatchException e) {
System.out.println("inappropriate input, please try again");
scan.next(); // this clears the scanner input }
}
}
System.out.println("your number is: " + num);
}
}
The line scan.next() must be there to clear the bad scanner input. You can try running the program
without it and giving bad input to see what happens.
Checking first if its an integer, then if its in the correct range (1-10):
while (true) {
System.out.println("Enter a number between 1 and 10: ");
try {
num = scan.nextInt();
if ((num >= 1) && (num <= 10)) {
break;
} else {
System.out.println("number must be between 1 and 10.");
}
} catch (InputMismatchException e) {
System.out.println("inappropriate input, please try again");
scan.next(); // this clears the scanner input / needs to be here
}
}
44
ICS4U - Java
Exercises:
a) Create a program that asks the user to enter test scores. Use a while loop to have them keep
adding scores until they are done and store the scores in an array or ArrayList. Use a try/catch
block to ensure appropriate input. Also make sure all scores are between 0 and 100. After
collecting the input, output all test scores in a nice way.
b) Pythagorean theorem program that makes sure inputs A and B are doubles, and also
positive values
c) make a program that asks the user to enter even numbers. Make it crash proof and not
accept odd numbers. Store them in an array and use a for loop at the end to output
them all in one line
45
ICS4U - Java
46
ICS4U - Java
1D Array:
int num[] = new int[] {1, 2, 3};
Looks like:
1 2 3
What is the value of
a) num[0] =
b) num[1] =
c) num[2] =
47
ICS4U - Java
or:
or:
We can also use nested for loops to put, say, random numbers in each cell:
We can output the table in a nice way the same way we did it in python; by building a string for
each row, outputting the entire line, then moving down to the next row:
String currentLine;
for (int r = 0; r<table.length; r++){
currentLine = ""; // blank string for a new row
for (int c = 0; c<table[0].length; c++){
currentLine += String.valueOf(table[r][c]) + " "; // add current cell
}
System.out.println(currentLine); // output the line
}
I often use “r” and “c” for “row” and “column” but you can still use “i" and “j” if you want.
48
ICS4U - Java
Exercises:
1) Create a table of 3 rows and 3 columns. The first row is first name, second row is last name,
third row is favorite colour. Ask two of your friends their favorite colour. Then manually create a
table and output it like this:
3) After drawing the entire table, ask the user which column to output, and then output the
information in this format:
4) Have the user input the desired number of rows and columns for a table of integers.
a. Create a table of that size and populate it with random numbers between 0 and 100.
b. Output the table
c. Calculate the average of each row and add that to each output line:
5) Generate 5 x 5 tables using for loops that look like these (no hard coding numbers):
*** the last one requires the use of modulus (%2 == 0) and a few if statements.
49
ICS4U - Java
50
ICS4U - Java
22: Methods
Methods (a.k.a. Functions) are ways of isolating code to perform specific functions. Here’s a method
called “greet” that asks for a user’s name and greets them with a lovely message:
Basic Method:
import java.util.Scanner;
class Scratch {
Notes:
1) The method is declared inside the main class (Scratch), but outside of the main method. I usually
put it above, but below is also fine.
2) “private” means it can only be used within this class. More on this later. You will need to have
that word there.
3) “static” is too much to get into here, but that word needs to be there.
4) “void” means it doesn’t return any values back to the main method.
Argument Version:
In this new version, the user enters their name in the main method, it is passed to the function as an
argument and the function outputs the message.
class Scratch {
1) When I call the great function, I am sending the name as an argument to the function.
2) The name from the main method is now stored in the local variable “name” in the greet
function.
51
ICS4U - Java
You can send as many arguments as you like of different data types, even arrays. For example:
Exercises:
Exercises:
1) Main method: ask the user for 3 foods (with 3 separate String). Send all three to a method called
favFoods(String food1, String food2, String food3) and output their three favorite foods in a fun
way.
2) Main method: ask the user for sides A and B of a right triangle. Send them to a method
getHypotenuse() that takes both sides as arguments. Calculate and output the hypotenuse.
3) Main method: generate 2 random die rolls 1-6. Send both rolls to the method getDieResults().
The method should output the following messages based on the sum:
7, 11 “winner!”
6 “tie!”
2 “snake eyes!”
Otherwise if its > 5 “greater than 5”
Otherwise, “less than 5”
4) Ask the user their country of birth and age. Send both to a method called isEligible(). If there
country of birth starts with “can” (ignore case) and they are at least 18, output “you are
eligible”. Otherwise, output “you are NOT eligble.”
52
ICS4U - Java
class Scratch {
53
ICS4U - Java
Here is a screenshot:
Notes:
Line 5: I changed the word “void” to “int” because this method returns an integer back to the
main method.
Line 5: you can have 2 arguments or as many as you want for your function.
Line 7: returns the sum back to the main method
Line 17: this line calls the add function, sends it both arguments (num1 and num2) which will be
stored in the functions local variables n1 and n2.
Line 17: the int total accepts the value returned by the function to be used later.
54
ICS4U - Java
1) Extend the above program to include methods that perform subtraction, multiplication and
division.
2) Takes the radius of a circle as the argument and returns the area.
private static double getCircleArea(double radius){}
4) Takes the length and width of a rectangular and returns the perimeter.
private static double getPerimeter(double length, double width){}
5) Takes the radius and height of a cylinder and returns the volume.
private static double getCylVol(double height, double radius){}
6) Takes no arguments, but returns a random coin flip String of “H” or “T”.
7) Takes the country of citizenship and age of the user and returns boolean true if they are eligible
to vote, or false if not. (They are eligible if they are at least age 18 and are citizens of Canada).
private static boolean isEligible(int age, String country){}
8) Takes a min and max integer. Returns a random number between them (inclusive). Bonus: make
it evenly weighted for the lowest and highest values.
private static int randInt(int min, int max){}
9) Extension: takes an integer for the size of an array, min and max, returns an array of that size
with random numbers between min and max.
private static int[] getRanIntArray(int size, int min, int max){}
10) Harder: Takes a double as value and the number of integers desired. Returns a String of that
double with the correct number of decimal places.
private static String formatDouble(double value, int decimals){}
55
ICS4U - Java
class Scratch {
Questions:
56
ICS4U - Java
class Scratch {
Exercises: write and implement each function to show me they are working. These are useful functions
you can use in future programs:
1) isNumeric: Write more general version of isInteger() called isNumeric(). It checks if the given
string is any number (e.g. a double), not just an integer.
2) print: Write a method called “print()” that uses System.out.println() to print a string, but doesn’t
require you to write all that out, for example:
3) random: write a function to generate a random number. It should take as arguments the
minimum and maximum value (e.g. 1 and 10) and return a random double between them. It
can use Math.random(), but this new function will be much more useful for you.
4) addArray: Write a method called addArray(double[] vals) that takes an array of doubles (vals) as
the parameter, adds them all up, and returns the sum.
5) avgArray: Write a method called avgArray() that takes an array of doubles and calculates and
returns the average. It should use your previous method addArray
57
ICS4U - Java
*** anytime you use a file reader or writer, there is the possibility of the program throwing an exception
if the file can’t be found / can’t be written to. You can use try/catch blocks, but generally speaking you
can also simply add throws IOException in the method signature.
Run the program. Find the file you made and open it to see what is inside.
Exercises:
If you want to append to an already-existing file without overriding what is already in there, change the
line to:
FileWriter fw= new FileWriter(fileName, true);
// true appends to existing file
e) Redo exercise (c) but allow rewriting. Run the program 3 times with new sentences. Instead of
asking for a file name, just write to “output.txt”.
f) Have the user input a minimum and maximum number. Output all odd numbers between both
values into “output.txt”.
58
ICS4U - Java
g) Redo exercise (f) but output them into “output.xls” (an excel spreadsheet). Open the file in Excel
or google sheets (ignore the warnings).
}//end of try
catch(IOException e){
System.out.println("This prints because requested file does not exist.");
}//end of catch
System.out.println(line);
}
If the filename is always the same, you can hardcode it rather than asking the user. You should
always use try/catch just in case the file isn’t in the right place.
59
ICS4U - Java
Class: FileReader
Method Description
FileReader(String opens a stream so that data may flow from
fileName) the file stored in the String fileName to
the program
Class: BufferedReader
Method Description
BufferedReader(Reader creates a container holding data arriving
fr) through the stream created by fr.
BufferedReader (fr, int n determines the number of bytes of data
n) held in the buffer at any given time
close() closes the buffer as well as the stream
read() returns the next character from the buffer
(-1 if at end of string)
readLine() returns a line of text. Returns null if at
end of file.
skip(long n) skips up to n characters, and returns the
number of characters skipped.
Exercises:
a) Create a file called information.txt. Make up 3 sentences and write them in the first three lines
of the file.
b) Read and output the first line.
c) Read and output the first word of each line
d) Try reading 10 lines and output each line. How do you know when you’ve reached the end of
your file?
e) Change program (e) to recognize when it reached the end of the information in the file. Have it
break out of the loop when it gets to the end, and count/output the number of lines of
information in the file
f) Write a program that writes 100 random numbers between 1 and 100 into a file called
“randomnums.txt”. Do this in a method. Then call a second method that reads the file and find
the average of all numbers. It should return the average back to the main method and output
the value.
g) Add to the previous program: it now first stores the 100 random values in an integer array. It
then goes through the array to write the data to a file, then reads from the file and stores the
data into a new array of the correct size.
60
ICS4U - Java
1)
// returns the number of lines in a .txt file
private static int getlines(String fileName){}
2)
// returns a specific line from a .txt file
private static String getline(String fileName, int line){}
3)
// takes a line from the getline method and returns the words as an array of
strings
// must be the exact size of the number of words - no padding
private static String[] getlinewords(String[] args) {}
4)
// returns every word in a .txt file as one String array. Uses the previous
method
private static String[] getallwords(String fileName){}
61
ICS4U - Java
// reading file
BufferedReader br = new BufferedReader(new FileReader(f));
System.out.println(br.readLine());
As this example shows, writing to a directory involves different syntax depending on the operating
system. You can specify the path based on the operating system. This code lets you check the operating
system:
String OS = System.getProperty("os.name");
System.out.println(OS);
But you can get many different versions of MAC OS so an exact name match is tricky. Instead, try:
String OS = System.getProperty("os.name").toLowerCase();
if(OS.contains("win")){
System.out.println("It's Windows");
}else if(OS.contains("mac")){
System.out.println("It's an Apple");
}
62
ICS4U - Java
Now you can tailor the file path based on the operating system.
Exercises:
63
ICS4U - Java
You can locate a specific item with an equation, without having to read the entire file up to that point.
E.g. if the item length is n bytes, then the item at location L is:
item = L * n – n = n(L-1)
RandomAccessFile is a class that writes to binary data files. To use it we must use:
a) import java.io.*;
b) throws IOException
//preparing to read: 30
raf.seek(8);
System.out.println(raf.readInt());
//preparing to read: 20
raf.seek(4);
System.out.println(raf.readInt());
64
ICS4U - Java
Exercises:
a) modify the program to write every multiple of 7 up to 100 with a for loop, and then output them
all with a for loop.
b) Modify (a) to store the values in an array before outputting them.
c) Use writeChar and readChar to write your first name in individual characters. Read them and
output them.
d) Modify (c) to store your name first in a String. Then use charAt() to write the chars into the file.
e) Add to program (b): use a for loop to read all the characters of your name and add them to a
string. After building the entire string, output the string.
f) Use writeLong / readLong to write the perfect squares of every integer from 1 – 1000. Then ask
the user which integer to look for. Calculate the position of that integer, seek that location and
output the value. Check your math to make sure you output the correct number.
65
ICS4U - Java
a) Name
b) Hours worked
c) Rate of pay (e.g. 20 20 dollars an hour)
Requirements:
1) Read the given rawdata.txt file. Store the employee names, hours and rates in three separate
arrays.
2) Output the information in a nice way.
3) Write it to a new file called “calcdata.txt”. It should hold:
a. Name
b. Total pay (hours * pay rate)
4) Use should be able to input an employees order in the file (e.g. record 0, 1, 2, …) and it should
read and output their name and total pay from calcdata.txt
66