Website snapshot

This commit is contained in:
Brandon Rozek 2020-01-15 21:51:49 -05:00
parent ee0ab66d73
commit 50ec3688a5
281 changed files with 21066 additions and 0 deletions

View file

@ -0,0 +1,40 @@
# CPSC 220 Computer Programming and Problem Solving Spring 2018
[Lecture 1 -- January 16](jan16)
[Lecture 2 -- January 18](jan18)
[Lecture 3 -- January 23](jan23)
[Lecture 4 -- January 25](jan25)
[Lecture 5 -- January 30](jan30)
[Lecture 6 -- February 1](feb1)
[Lecture 7 -- February 6](feb6)
[Lecture 8 -- February 8](feb8)
[Lecture 9 -- February 13](feb13)
[Lecture 10 -- February 20](feb20)
[Lecture 11 -- February 27](feb27)
[Midterm Review](midtermreview)
[Lecture 12 -- March 13](mar13)
[Lecture 13 -- March 20](mar20)
[Lecture 14 -- March 22](mar22)
[Lecture 15 -- March 27](mar27)
[Lecture 16 -- March 29](mar29)
[Lecture 17 -- April 3](apr3)

View file

@ -0,0 +1,39 @@
# Lecture for April 3rd
## Inheritance
The *base class*, *super class*, or *parent class* is the initial class that we are working with. Let's say that you want to *extend* the class, or add additional functionality. The class that inherits from the parent class is called the *child class*, *subclass* or *derived class*.
## Child Class Syntax
```java
public class Truck extends Car {
// Truck Appropriate Fields
// Necessary methods for truck
}
```
This code adds all the methods from Car into the Truck class. You can then add methods that is specific to a Truck into the Truck class.
A child class has all parent fields and access to all parent methods!
## Visibility Modifiers
Recall the words `public` and `private`
The `public` modifier makes the field/method accessible by any class
The `private` modifier makes the field/method only accessible within the method itself
The protected modifier makes the field/method accessible within the same class or any subclasses.
## Overriding a Method
You can override a parent class method by declaring a method in the child class with the same...
- name
- number of paramters
- parameter types
but this method would have different behavior!

View file

@ -0,0 +1,66 @@
# Lecture for February 1st
## Control Structures
In this class we will talk about three types of control structures
- Sequential
- Selection
- Repetition
Sequential is what is most familiar to us. Write the lines from top to bottom and it executes it in that order
### Selection
Selection depends on the question of `if`.
If it is raining, wear boots
```java
if (raining) {
wearingBoots = true;
}
```
If you want something to happen also when it is not true, consider an `if-else` statement
If the light is off, turn it on.
Otherwise, turn it on
```java
if (lightIsOn) {
lightIsOn = false;
} else {
lightIsOn = true;
}
```
Sometimes you can have multiple branches depending on a condition. Let us take a stop light as an example
```java
if (light == "red") {
car.stop()
} else if (light == "yellow") {
car.slow()
} else {
car.go()
}
```
## String comparison
There is a specific method in the `String` class when it comes to checking for string equality
```java
boolean equals(String s)
```
Let us look at an example
```java
String word = "hello";
boolean ans = word.equals("hello"); // Returns true
boolean ans2 = word.equals("Hello"); // Returns false
```

View file

@ -0,0 +1,74 @@
# Lecture for February 13
## Loops
###Why Loops?
While some check is true, repeat the work.
While the cookies aren't baked, keep baking
### Loop Building Process
1. Identify one test that must be true when the loop is finished
2. Use the **opposite** form of the test
3. Within loop, make *progress* towards completion of the goal.
### While syntax
```java
while (expression) {
// Loop body executes if expression is true
}
// Statements execute after expression is false
```
### Getting Input (Songs in a Playlist Psuedocode)
```java
// Ask user about first song
while (user says play next song) {
// play next song
// ask user about next song
}
```
### Nested Loops
You can have loops inside loops
```java
int outer = 1;
while (outer < 4) {
int inner = 1;
while (inner < 4) {
System.out.println(outer + ":" + inner);
inner++;
}
outer++;
}
```
This code does the following
```reStructuredText
1:1
1:2
1:3
2:1
2:2
2:3
3:1
3:2
3:3
```
### Break Down the Problem
Never write the entire program at once! This makes it incredibly hard to debug. Instead break it into small parts.
Write one part -> debug until it works
Write second part -> debug until it works
This way you know which part of your code failed, instead of having everything fail.

View file

@ -0,0 +1,94 @@
# Lecture for February 20th
## Reading a File
You can get input from a file instead of from the terminal
```java
FileInputStream fileIn = new FileInputStream("myFile.txt");
// Our familiar Scanner
Scanner scnr = new Scanner(fileIn);
// We can use our usual Scanner methods
String line = scnr.nextLine();
fileIn.close(); // Remember to close the file when you're finished with it!
```
### Reviewing Scanner Methods
To understand some of the Scanner methods we need to be aware of the "newline" character. This character is equivalent to the `Enter` button on the keyboard.
`scnr.nextLine()` This get's all the characters in the buffer up to the newline character.
`scnr.next()` Grabs the characters in the next "token". Tokens are usually separated by any whitespace type character (spaces, enters, tabs, etc.)
## Writing to a File
Prints information to a file instead of to the screen
```java
FileOutputStream fileOut = new FileOutputStream("myOutfile.txt");
PrintWriter out = new PrintWriter(fileOut);
out.println("Print this as the first line.");
out.flush(); // Pushes the file changes to the file
fileOut.close(); // If you forget this then it won't remember your changes
```
## Arrays
Arrays are containers of fixed size. It contains a fixed number of values of the **same type**. (Ex: 10 integers, 2 strings, 5 booleans)
Declaration
```java
int[] array; // This declares an integer array
```
Initialization
```java
array = new int[7]; // This states that this array can hold up to 7 integers
```
Storing a value in an array
- Square bracket notation is used
```java
int[] array = new int[7];
array[0] = 5; // Stores 5 into the first slot
```
Now let us attempt to retrieve the value
```java
int temp = array[0];
System.out.println(temp); // Prints "5"
```
### Traversing an Array
Let's say we have the following array
```java
int[] numbers = {3, 5, 2, 7, 9};
```
Let's print out each of the values in the array
```java
for (int i = 0; i < numbers.length; i++) {
System.out.print("value in " + i " is " + numbers[i]);
}
```
### Finding the maximum value in an Array
```java
int highest = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > highest) {
highest = numbers[x];
}
}
```

View file

@ -0,0 +1,91 @@
# Lecture for February 27th
## Review for midterm
Chapter 1 -- Code Style, API
Chapter 2 -- Variables & Assignments, strings
Chapter 3 -- input & output
Chapter 4 -- branches (if, if/else, switch)
Chapter 5 -- loops (while, for), scope
Chapter 6 -- File Reading and Writing
## Separated vs Connected Branches
What is the output of this code?
```java
String preferredLanguage = "Spanish";
if (preferredLanguage.equals("Chinese")) {
System.out.println("Ni hao!");
}
if (preferredLanguage.equals("Spanish")) {
System.out.println("Hola!");
}
if (preferredLanguage.equals("French")) {
System.out.println("Bonjour!");
}
if (preferredLanguage.equals("German")) {
System.out.println("Gutentag!")
} else {
System.out.println("Hello!")
}
```
The output is
```reStructuredText
Hola!
Hello!
```
This is because each of the if statements are independent from each other. Whether or not the if statement gets check is not affected by the if statements around it.
Since the preferred language equals Spanish it outputs `Hola!` But since the language is also *not German* it prints out `Hello!` as well.
## Using an Array
Square brackets notation is used to access elements, array slots can be used as variables
```java
int[] array = new int[7]; // Creates an integer array of size 7
array[0] = 5;
```
## Swapping Elements
You can swap `x` and `y` in the following way with a *temporary* variable
```java
int x = 6;
int y = 1;
int temp = x;
x = y;
y = temp;
```
## Two-Dimensional Arrays
```java
// Creates a 2D array of two rows and three columns
int[][] a = new int[2][3]
```
You can access an element of this 2D array using the conventional square bracket notation
```java
a[0][0] = 5;
```

View file

@ -0,0 +1,139 @@
# Lecture for February 6th
## If Statements -- Cont.
Inside the parenthesis of the `if` statement must be a boolean expression. This is an expression that evaluates to either `true` or `false`. We can do more complex boolean expressions through logical operators.
## Logical Operators
NOT `!a` this is true when `a` is false
AND `a && b ` this is true when both operands are true
OR `a || b` this is true when either a is true OR b is true
## Truth Tables
- Show all possible outcomes
- It breaks the expression down into parts
### Not
Let's look at the most simplest case. Not.
| a | !a |
| ----- | ----- |
| true | false |
| false | true |
### AND
| a | b | a && b |
| ----- | ----- | ------ |
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
Notice here that `a && b` is only true when both `a` and `b` are true.
### OR
| a | b | a \|\| b |
| ----- | ----- | -------- |
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
Notice here that `a || b` is only false when both `a` and `b` are false.
## Precedence (Order of Operations)
| | |
| --------------------------------- | ------------------- |
| Parenthesis | `()` |
| Logical Not | `!` |
| Arithmetic Operators | `*` `/` `%` `+` `-` |
| Relational Operators | `<` `<=` `>` `>=` |
| Equality and Inequality operators | `==` `!=` |
| Logical AND | `&&` |
| Logical OR | `||` |
## Playing with Truth Tables Example
### a && !b
| a | b | !b | a && !b |
| ----- | ----- | ----- | ------- |
| true | true | false | false |
| true | false | true | true |
| false | true | false | false |
| false | false | true | false |
### !a || b
| a | b | !a | !a \|\| b |
| ----- | ----- | ----- | --------- |
| true | true | false | true |
| true | false | false | false |
| false | true | true | true |
| false | false | true | true |
### !(a || b && c)
| a | b | c | b && c | a \|\| (b && c) | !(a \|\| b && c) |
| ----- | ----- | ----- | ------ | --------------- | ---------------- |
| true | true | true | true | true | false |
| true | true | false | false | true | false |
| true | false | true | false | true | false |
| false | true | true | true | true | false |
| true | true | false | false | true | false |
| true | false | true | false | true | false |
| false | true | true | true | true | false |
| false | false | false | false | false | true |
### !a || b && c
| a | b | c | !a | b && c | !a \|\| b && c |
| ----- | ----- | ----- | ----- | ------ | -------------- |
| true | true | true | false | true | true |
| true | true | false | false | false | false |
| true | false | true | false | false | false |
| false | true | true | true | true | true |
| true | false | false | false | false | false |
| false | true | false | true | false | true |
| false | false | true | true | false | true |
| false | false | false | true | false | true |
## Distributive Property of Logical Operators
The following statements are equivalent
`!(a && b)` is equivalent to `!a || !b`
Notice how when you distribute the `!` you have to flip the operand as well. `&&` becomes `||`
Same is true for the following example
`!(a || b)` is equivalent to `!a && !b`
`!(a || b && c)` is equivalent to `!a && (!b || !c)`
## Short Circuit Evaluation
In an `&&` (AND) statement, if the left side is `false`, there is no need to evaluate the right side. Since it's going to be false anyways!!
```java
false && true; // FALSE no matter what the right side is
```
In an `||` (OR) statement, if the left side is `true, there is no need to evaluate the right side. Since it's going to be true by default!!
```java
true || false; // TRUE no matter what the right side is
```
Java takes this shortcut by default for efficiency reasons

View file

@ -0,0 +1,112 @@
# Lecture for February 8th
##Switch Statements
Another way to perform multiway branching. Comparing a variable and constant values (`String`, `int`, `char`)
Switch statements cannot be used with `boolean`, `double`, or `float`s
### Syntax
```java
switch (variable) {
case value1:
// Do something
break;
case value2:
// Do something else
break;
//...
default:
// If all else fails do this
break;
}
```
`case` is a reserved word that means "when our variable in consideration is equal to..."
If you forget the `break` keyword, then the program will keep doing the work of all the statements until it hits a `break` keyword.
### Example Switch Syntax
```java
switch (birthday) {
case 1:
birthstone = "garnet";
break;
case 2:
birthstone = "amethyst";
break;
// ....
default:
System.out.println("Not valid");
break;
}
```
## Comparing Strings Relationally
Comparing strings are based on the ASCII value of characters
Sorting strings will result in strings being in alphabetical or reverse alphabetical order. The values of the strings are compared character by character from the left with each ASCII value.
To compare strings use the `compareTo()` method. Here is the format of the call
```java
str1.compareTo(str2)
```
This returns a *negative number* when `str1` is less than `str2`
This returns `0` when `str1` is equal to `str1`
This returns a *positive number* when `str1` is greater than `str2`
### Example
```java
String a = "apple";
String b = "banana";
int x = a.compareTo(b); // x = -1
int y = b.compareTo(a); // y = 1
```
## Ternary Operator
With a ternary operator, you can shorten statements where a value is determined by an if statement
```java
String output = "";
if (movieRating > 4) {
output = "Fan favorite";
} else {
output = "Alright";
}
```
Is equivalent to
```java
String output = "";
output = (movieRating > 4)? "Fan favorite": "Alright";
```
### Another Example
```java
double shipping;
if (isPrimeMember) {
shipping = 0;
} else {
shipping = 3.99;
}
```
Is equivalent to
```java
double shipping = (isPrimeMember)? 0: 3.99;
```

View file

@ -0,0 +1,47 @@
# Lecture for January 16 2018
## Comments
You can use multi-line comments or single line comments to note about a piece of code. This helps you so that you don't forget what was happening in the code
```java
/* Multi Line Comment
I am multiple lines woo!
*/
System.out.println("Hello"); // I am an inline comment
```
### Javadocs
This is a standardized method in Java to describe your functions and classes
```java
/**
* This is a Javadoc comment. A description of your class should appear here
* @author Brandon
* @version 2018
*/
public class Example{
/** Another Javadoc comment.
* A description of your program should go here
*/
public static void main(String[] args) {
}
}
```
## Variables
Convention in Java is for all of your functions/method names to be lowercase.
Class names should be title cased, each word is capitalized ex: `IntroExample`
## Java API
The Java API is publicly accessible and is extremely useful for finding methods in existing classes.
The API documentation for the `String` class is located here: https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/String.html

View file

@ -0,0 +1,188 @@
# Lecture for January 18
## Variables and Assignment
Think about variables as buckets that hold information. Once the bucket is created, only one type of item can go in the bucket.
```java
sand bucket1;
```
We can say that bucket1 is of type `sand`, that means the only thing that can go in the bucket is sand.
```java
int bucket1;
double bucket2;
```
From the two lines above, we have *declared* the variable.
Variables store state, they are a name for a location in memory.
Always remember to initialize your variables. Otherwise there's nothing in the bucket!
```java
bucket1 = 5;
```
You can combine both the declaration and initialization
```java
int count = 15;
```
Remember when dealing with variables to stay true with the type, don't mix a bucket of water with a bucket of sand.
We can update `count` to contain a true value
```java
count = 55;
```
`count` no longer has the value of `15` in it. There's no record of it! It has been overwritten with the value `55`
### Primitive Types
There are 8 primitive types in Java
- boolean
- char
- byte
- short
- int
- long
- float
- double
byte through double are all *numeric* types
#### Boolean
`boolean` can only be equal to `true` or `false`
```java
boolean student = true;
```
#### Char
Stores a single character from the Unicode set
There are 16 bits per character which adds up to 65,536 characters
ASCII is the US subset of the characters. You can look this up online when needing to deal with ASCII values
```java
char firstLetter = 'A';
```
### Numeric types
The different numeric types determine the precision of your number. Since numbers are not represented the same in the computer as they are in real life, there are some approximations.
The default type you can use your code is `int` for integers and `double` for numbers with a decimal point
There are certain types of operations you can perform on numeric type
| Symbol | Meaning | Example | Value |
| ------ | --------------- | ---------- | ----- |
| + | addition | 43 + 8 | 51 |
| - | subtraction | 43.0-8.0 | 35.0 |
| * | multiplication | 43 * 8 | 344 |
| / | division | 43.0 / 8.0 | 5.375 |
| % | remainder / mod | 43 % 8 | 3 |
| - | unary minus | -43 | -43 |
#### Increment/ Decrement
There are two types of in/decrementers postfix and prefix
Postfix:
```java
int x = 0;
int y = 7;
x++; // Shortcut for x = x + 1
y--; // Shortcut for y = y - 1
```
Prefix
```java
int x = 0, y = 7, z;
z = y * x++; // Equivalent to (y * x) + 1 = 7 * 0
z = y * ++x; // Equivalent to y * (x + 1) = 7 * 1
```
### Data Conversion
There are two types of data conversion, implicit and explicit
The compiler can perform implicit data conversion automatically.
Performing an explicit data conversion requires additional work on the programmer's part
A conversion is implicit if you do **not** lose any information in it
```java
double price = 6.99;
int sale = 3;
double total = price - sale;
```
A *cast* is an explicit data conversion. This is requested by a programmer, this can lead to loss of information
```java
int nextChar = 'b';
Character.isAlphabetic( (char) nextChar); // Let's you print the actual letter 'b' instead of the number corresponding to it
float price = 6.99;
int cost = (int) price; // cost is now 6
```
### Printing variables
You can print the values of variables using `System.out.println` and `System.out.print`
The difference is that `System.out.println` adds a new line at the end. Meaning the next print out will be on the next line.
```java
int cost = 5;
double sale = .30;
System.out.print(cost);
System.out.print(sale);
// Prints out '5.30`
System.out.println(cost);
System.out.println(sale);
// Prints out '5'
// Prints out '0.30'
```
To add a space between two variables in a print, add `" "` to the expression in between the two variables
```java
System.out.println("The total cost is " + 5 " dollars and" + " " + 93 + " cents");
// The total cost is 5 dollars and 94 cents
```
### Input from User
You can get import from the user, we can do this using the `Scanner` class.
First import it at the top of your file
```java
import java.util.Scanner;
```
All you can do with `Scanner` is outlined in the Java API at this link https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Scanner.html
Create a Scanner object
```java
Scanner input = new Scanner(System.in);
System.out.print("Please enter an integer: ");
price = input.nextInt(); // The integer that the user inputs is now stored in price
System.out.println("Your input: " + price);
```

View file

@ -0,0 +1,92 @@
# Lecture for January 23
## Java Class
In Java, your code must live in a class.
```java
public class NameOfClass {
public static void main(String[] args) {
// All program code
}
}
```
It is important that `NameOfClass` is named meaningfully for the code. It is convention to use CamelCase when using classes. (Capitalize your class names!)
All methods have a method signature, it is unique to it. For main it is the words `public static void` and the argument `String[] args`.
`public` means that any other piece of code can reference it.
`void` means that the method returns nothing
`main` is the name of the method. It is important to have `main` since that tells the Java Interpreter where to start in your program.
`String[] args` is the command line arguments inputted into the program. For this part of the class, we don't need to worry about it.
If you noticed `String` is a class, it is not a primitive type. This is denoted in Java by having it capitalized.
## Arithmetic Expressions
There is an order of operations in programming as well. It goes like this:
1. Parenthesis
2. Unary Operations
3. *, /, %
4. +, -
And from there you read from left to right.
## Constant Variables
These are variables that can never be changed
```java
final int MINUTES_PER_HOUR = 60
```
The keyword `final` indicates to the Java compiler that it is a constant variable.
By convention, constants are in all caps with underscores being separated between the words
## Java Math Library
There are some arithmetic expressions that we want to be able to do and we cannot achieve that simply with the standard operations
| Method | Description |
| -------------- | ----------------------------- |
| Math.sqrt(x) | square root |
| Math.abs(x) | absolute value |
| Math.pow(a, b) | exponentiation $a^b$ |
| Math.max(a, b) | returns the maximum of a or b |
| Math.min(a, b) | returns the minimum of a or b |
| Math.round(x) | rounds to the nearest integer |
## Example: Finding Areas
```java
public class MoreVariables
public static void main(String[] args) {
// Decrate a variable
int x;
// Initialize ia variable
x = 5;
// Area of a square
int squareArea = x * x;
System.out.println("Area of a square: " + squareArea);
double newSquare = Math.pow(x, 2);
System.out.println("Area of square: " + newSquare);
// Area of Circle
final double PI = 3.14159;
double radius = 3;
double circleArea = radius * radius * PI;
System.out.println("Area of circle: " + circleArea);
}
```

View file

@ -0,0 +1,137 @@
# Lecture for January 25
## Strings
These are concatenated chars
```java
'd' + 'o' + 'g' // equivalent to "dog"
```
```java
"straw" + "berry" // strawberry
```
Strings are denoted by double quotes `""` rather than a string which is denoted by single quotes `''`
String is not a primitive type, it is a class. Hence, why it is capitalized in Java.
The `java.lang.String` is automatically imported in Java.
To declare and initialize a String
```java
String name = "Henry";
```
In memory it appears as
| H | 'e' | 'n' | 'r' | 'y' |
| ---- | ---- | ---- | ---- | ---- |
| | | | | |
### String Methods
```java
int length()
```
```java
boolean equals(String another)
```
```java
boolean startsWith(String prefix)
```
```java
boolean endsWith(String suffix)
```
```java
String substring(int start, int end)
```
```java
int indexOf(int ch)
```
```java
String toLowerCase()
```
### Using String Methods
```java
char first = name.charAt(0);
```
Remember in Java, that it starts counting from zero! If you try to access a letter that doesn't exist, it will produce an `IndexOutOfBounds` error.
## Errors
There are two types of errors, compile-type errors and run-time errors. Later we will talk about debugging skills such as making "breakpoints" in your code so you can analyze the different variable values.
### Compile Time Errors
Compile time errors are generated due to syntax errors. Forgot a semicolon? Missing a brace?
### Run-time Errors
These are logic errors. Not derived from syntax errors. An example of one that was discussed earlier is the `IndexOutOfBounds` error.
## Tricky Thing About Input
Let's talk about input right now. Let's say you have the following scenario
```java
Scanner input = new Scanner(System.in);
System.out.println("Enter pet's age: ");
int age = input.nextInt();
System.out.println("Enter pet's name: ");
String name = input.nextLine();
System.out.println("Enter pet's breed: ");
String breed = input.next();
```
Then when we start to run the program...
```reStructuredText
Enter pet's age:
14
Enter pet's name:
Enter pet's breed:
Labradoodle
```
Why did it skip pet's name? Let's run through the process again
```reStructuredText
Enter pet's age:
14 [ENTER]
Enter pet's name:
Enter pet's breed:
Labradoodle
```
Here the [ENTER] key gets saved into name.
To resolve this, just use an `input.nextLine()` to throw away that [ENTER]
```java
Scanner input = new Scanner(System.in);
System.out.println("Enter pet's age: ");
int age = input.nextInt();
System.out.println("Enter pet's name: ");
input.nextLine();
String name = input.nextLine();
System.out.println("Enter pet's breed: ");
String breed = input.next();
```

View file

@ -0,0 +1,91 @@
# Lecture for January 30
## Random Number Generator
One of the ways you can do a random number generator is through this method:
Import a class called random
```java
import java.util.Random;
```
Then you need to create a `Random` object
```java
Random rand = new Random();
```
After this you can call the `nextInt()` method to get a random number between 0 and $2^{32}$
```java
int randInt = rand.nextInt();
```
If you don't want a random number between 0 and $2^{32}$ but instead to another maximum value, then you can call the `nextInt` method inserting the max integer as a parameter.
Random Integer from 0-10 (not including 10)
```java
int randInt2 = rand.nextInt(10);
```
## Output
We have already encountered `System.out.println` and `System.out.print` but let us go over the differences again.
`System.out.println()` prints the contents inside the parenthesis and appends a newline character afterwards so that the next output is on a new line
`System.out.print()` prints the contents inside the parenthesis and does not output a newline character
### Formatting Output
If you want more control on how your output is displayed, it is recommended that you use `System.out.printf` to format your output
First, you need to specify your type using the % instruction
- d for integer
- f for decimal
Example:
```java
int sum = 50;
System.out.printf("Total = %d", sum);
```
This outputs
```reS
Total = 50
```
Notice here that there is no concatenation required like the previous two methods, instead you insert the variables as parameters
Let us deconstruct the % instruction
% __ __ . __ __
The first underline is the + - 0 space (sometimes we want to pad the money with zeros)
The second underline is the width of the text
The third underline is the number of decimal places
The the final underline is the specifier `f` for decimal and `d` for integer
<u>Example</u>
```java
double amount = 0.5;
System.out.printf("Total Due: %0.2f")
```
This outputs
```reStructuredText
Total Due: 0.50
```

View file

@ -0,0 +1,78 @@
# Lecture for March 13th
## Methods
Methods are small blocks of statements that make it easier to solve a problem. It usually focuses on solving a small part of the overall problem.
Usually in methods you provide some sort of input and get some output out of it.
### Advantages
- Code readability
- Modular program development (break up the problem in chunks)
- Incremental development
- No redundant code!
### Method definition
Consists of a method name, input and output and the block of statements.
Usually this is succinctly written using JavaDocs which is what you see in the JavaAPI
### Method Call
A method call is the execution of the method. The statements defined in the method is what will execute.
### Method Stubs
Recall from method definition the parts of the method definition. Now look at the following method
```java
String[] split(String s)
```
The output here is `String[]`
The method name is `split`
The input is `String s`
## Modular Programming
Let us look at the following example:
The program should have a list of grocery prices. It should be able to calculate the total cost of groceries. The store gives a student discount of 5%. The program should calculate this discount and update the total, it should calculate and add the 2.5% tax.
- First you should add it all up
- Then compute the discount
- Then add the tax
## Parts of a method definition
```java
public static int timesTwo(int num) {
int two = num * 2;
return two;
}
```
It first starts off by declaring the visibility `public`
The return type if `int`
The method name is `timesTwo`
The input parameter is `int num`
Between the curly braces is the *body* of the method
## Calling a Method
```java
int a = 5;
int b = 3;
int ans = multiply(a, b)
```
The method call is `multiply(a, b)` and the result is stored in the variable `ans`

View file

@ -0,0 +1,32 @@
# Lecture for March 20th
## Unit Testing
With unit testing you are able to test small parts as you go. With unit testing, you can test many examples and border cases (extreme inputs) to see how your code reacts to different input.
## Variable Scope
A variable declared inside a method is only accessible inside that method.
A good rule of thumb is that if a variable is declared within curly braces {} then it does not exist outside that curly brace.
## Method Overloading
Sometimes we need to have methods with the same name but different input parameters.
```java
public static int multiply(int a, int b) {
return a * b;
}
```
This method only works with integers, what if we want to multiply two doubles?
We can overload the method by declaring another method with the same name.
```java
public static double multiply(double a, double b) {
return a * b;
}
```

View file

@ -0,0 +1,72 @@
# Lecture on March 22nd
## Method Documentation
Java has a special way that you can document your methods such that it will create documentation for you if you follow the convention.
The Java API actually uses this technique to produce its own documentation.
To create this, indicate a method with special comments that begin with `/**` and ends with `*/`
It contains *block tags* that describe input and output parameters
`@param` and `@return`
### Example
```java
/**
* @param y an integer to sum
* @param x an integer to sum
* @return the sum of x and y
*/
public int multiply(int x, int y) {
return x + y;
}
```
## Passing a Scanner
We only want to create one **user input scanner** per program, we also only want one **file input scanner** per program.
If a method needs a scanner, you can pass the one you already created in as an input parameter.
## Array as Input Parameter
Primitive types (`int`, `char`, `double`, etc.) are passed by value. Modifications made inside a method cannot be seen outside the method.
Arrays on the other hand, is pass by reference. Changes made to an array inside the method can be seen outside the method.
```java
public static void main(String[] args) {
int[] nums = {1, 3, 5, 7, 9};
timesTwo(nums);
}
public static void timesTwo(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2;
}
}
```
At the end of the `timesTwo` method call, the variable `nums` would have `{2, 6, 10, 14, 18}`
## Sizes of Arrays
### Perfect Size Arrays
When we declare an array, Java automatically fills every slot of the array with the type in memory. So if you know that you need exactly 8 slots, then you only ask for 8.
### Oversize Arrays
This is when we don't know how many slots we need. Therefore, we ask for more than we think we'll need. That way we don't go out of bounds.
If we do this, then we don't know how many elements we have already inserted into the array. Since the length is the number of slots.
So we can create another variable, which will keep track of the index in where we can add the next element.
We use oversized arrays when the size of the array is unknown or may change.

View file

@ -0,0 +1,140 @@
# Lecture for March 27
## In the Real World...
Objects are known for having characteristics. A car has on average 4 wheels, 2-4 doors, a steering wheel.
Objects can perform actions. A car can drive, hold cargo, and honk.
## In the Programming World...
Object-Oriented Programming
- Focuses on objects
- Are not linear
- Adds organization to a program
- Fits with human cognition (making abstractions)
## Class Structure
```java
public class Classname {
// Fields
// Constructors
// Methods
}
```
## Fields
Fields are instance variables, they store values, help define state, and exist in memory for the lifetime of the object.
```java
public class Car {
private double price;
private double gas;
}
```
## Constructor
We can build an object through a constructor. It is a special kind of method, this method requires that you not have a return type and that you name it the same as the class itself.
Constructors help set default field values for the different properties of our class.
```java
public class Car {
// Begin Constructor
public Car(double cost) {
this.price = cost;
this.gas = 0;
}
// End Constructor
private double price;
private double gas;
}
```
**Note:** The `this` keyword refers to the object's fields. This helps keep it separate from other variables you can create in the method and the input parameters you receive.
## Accessor Method - "Getter"
We like to classify methods into two types, accessors and mutators.
Getter methods return a copy of an instance field. It does not change the state of the object.
```java
public double getPrice() {
return this.price;
}
```
## Mutator Method - "Setter"
This type of method modifies an instance field. It does not return anything and changes the state of the object.
```java
public void setPrice(double cost) {
this.price = cost;
}
```
## Example of Car Class In All Its Glory
```java
public class Car {
// Instance Variables
private int mpg;
private double price;
// Constructors
public Car() {
this.price = 0;
this.mpg = 0;
}
public Car(double cost, int mpg) {
this.price = cost;
this.mpg = mpg;
}
// Accessors
public double getPrice() {
return this.price''
}
public int getMpg() {
return this.mpg;
}
// Mutators
public void setPrice(double cost) {
this.price = cost;
}
public void setMpg(int mpg) {
this.mpg = mpg;
}
}
```
## Using Classes
Just like how we used the `Scanner` class, we can also use our new `Car` class.
```java
public class TestCar {
public static void main(String[] args) {
// Declare an object reference
Car c;
// Initialize the object
c = new Car();
// Update the fields of the object
c.setPrice(3000);
c.setMpg(22);
// Print object information
System.out.println("Price is " + c.getPrice() )
}
}
```

View file

@ -0,0 +1,67 @@
# Lecture for March 29th
## Enumerated Types
These represent a fixed set of constants and include all possible values within them.
Let's look at coins. On a daily basis in the US, we use the following coins:
- Penny
- Nickel
- Dime
- Quarter
Other examples include the days of the week, clothes sizes, etc.
## Enum Syntax
Let's define an `enum` type
```java
public enum Coin { PENNY, NICKEL, DIME, QUARTER}
```
Now declare and initialize a variable
```java
Coin myCoin = Coin.PENNY
```
## Arrays vs ArrayList
Arrays require you to say upfront, how many slots you need. ArrayLists are more flexible since you can change the length of the array during Runtime.
Arrays can store objects and primitives such as `int`, `char`, `boolean`, etc.
ArrayLists can only store objects.
### How to declare an ArrayList
```java
ArrayList<objectType> list = new ArrayList<objectType>();
```
### Differences between getting the length of the array
**Array**
```java
int length = array.length;
```
**ArrayList**
```java
int length = array.size();
```
## For Each Loop
This is a special loop in where you tell it to go through all the elements of the array, without specifying an index.
```java
for (String b : buildings) {
System.out.print(b);
}
```

View file

@ -0,0 +1,45 @@
# More Midterm Review
Let us suppose that we have the following array
```java
int[] b = {11, 12, 15, 16, 21}
```
## Increase all elements by 2
```java
for (int i = 0; i < b.length; i++) {
b[i] += 2;
}
```
## Print all elements of array
```java
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
```
## Sum all the elements of an array
```java
int sum = 0;
for (int i = 0; i < b.length; i++) {
sum += b[i];
}
```
## Access Last Element of Array
```java
System.out.println(b[b.length - 1]);
```
## Access the middle element
```java
System.out.println(b[b.length / 2]);
```