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

0
content/ta/_index.md Normal file
View file

View file

@ -0,0 +1,39 @@
# CPSC 220 Computer Programming and Problem Solving Fall 2017
[Lecture 3 -- September 6](sept6)
[Lecture 4 -- September 11](sept11)
[Lecture 7 -- September 20](sept20)
[Lecture 9 -- September 25](sept25)
[Lecture 10 -- October 2](oct2)
[Lecture 11 -- October 4](oct4)
[Lecture 12 -- October 9](oct9)
[Lecture 13 -- October 11](oct11)
[Lecture 15 -- October 18](oct18)
[Lecture 16 -- October 23](oct23)
[Lecture 17 -- October 25](oct25)
[Lecture 18 -- October 30](oct30)
[Exam 2 Review -- October 30](exam2review)
[Lecture 19 -- November 6](nov6)
[Lecture 20 -- November 13](nov13)
[Lecture 21 -- November 15](nov15)
[Lecture 22 -- November 20](nov20)
[Lecture 23 -- November 27](nov27)
[Lecture 25 -- December 6](dec6)

View file

@ -0,0 +1,125 @@
# Final Review December 6
## Classes
Here is how you can create a class called "Employee" with a non-default constructor (a constructor that takes parameters) and a getter and setter
```java
public class Employee {
// Our private variables
private String name;
private double salary;
// Non-default constructor
public Employee(String name, double salary) {
this.name = name;
this.salarly = salary;
}
// This is a getter
public string getName() {
return name;
}
public double setSalarly(double salary) {
this.salary = salary;
}
}
```
## For Loops + Arrays
For loops are constructed in the following way
`for (initialization; condition to stop; increment to get closer to condition to stop)`
```java
//Assume an array with variable name array is declared before
for (int i = 0; i < array.length; i++) {
// This code will loop through every entry in the array
}
```
Note that you don't always have to start from zero, you can start anywhere from the array.
## For Loops + Arrays + Methods
This is an example of how you can take in an array in a method
```java
public static boolean isEven(int[] array) { // <-- Note the int[] array
for (int i = 0; i < array.length; i++) { // Iterate through the entire array
// If you find an odd number, return false
if (array[i] % 2 == 1) {
return false;
}
}
// If you didn't find any odd numbers, return true
return true;
}
```
## File I/O
Let's say that you have the following file
```
4
chicken
3
salad
```
And you want to make it so that you take the number, and print the word after it a certain number of times. For this example we would want to see the following
```java
chicken chicken chicken chicken
salad salad salad
```
Here is the code to write it
```java
public static void printStrings() {
FileInputStream file = new FileInputStream("stuff.txt"); // File contents are in stuff.txt
Scanner scnr = new Scanner(file); // Scanner takes in a file to read
while (scnr.hasNext()) { // While there are still stuff in the file to read
int number = scnr.nextInt(); // Grab the number
String word = scnr.next(); // Grab the word after the number
// Print the word number times
for (int i = 0; i < number; i++) {
System.out.print(word);
}
// Put a new line here
System.out.println();
}
}
```
## Recursion
Look at handout and carefully trace recursion problems
## 2D Arrays
Declare a 2D int array with 4 rows and 7 columns
```java
int[][] dataVals = new int[4][7];
```
A 2D array with 4 rows and 7 columns has 7 * 4 = 28 entries.
If you want to sum up all the numbers in a 2 dimensional array, do the following
``` java
// Assume numbers is declared beforehand
int sum = 0;
for (int i = 0; i < numbers.length; i++) { // Loop through every row in the 2D array
for (int j = 0; j < numbers[i].length; j++) { // Loop through every column in a row
// This code now looks at one entry in a 2D array
sum += numbers[i][j];
}
}
```

View file

@ -0,0 +1,62 @@
# Exam Review Partial Answer Sheet
Write a Java method to sum values of an array
```java
// Assume variable numbers is an array of 10 integers
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
```
Write a Java method to test if an array contains a specific value
```java
// Assume variable numbers is an array of 10 integers
int numWanted = 4;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == numWanted) {
System.out.println("The number " + numWanted + " was found!");
found = true;
}
}
if (!found) {
System.out.println("The number " + numWanted + " was not found!");
}
```
Write a Java method to find the index of an array element
```java
// Assume variable numbers is an array of 10 integers
int numWanted = 4;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == numWanted) {
System.out.println("The index of number " + numWanted + " is " + i);
}
}
```
How many lines will the following loop print when it is run?
```java
int i = 0;
while (i <= 6) {
System.out.println("i is now " + (i));
i++;
}
```
```
i is now 0
i is now 1
i is now 2
i is now 3
i is now 4
i is now 5
i is now 6
```

View file

@ -0,0 +1,221 @@
# Lecture for November 13
## File IO (Cont.)
Last class we talked about reading from files, we can also write to files.
### Import necessary libraries
First you must import all of the necessary libraries
```java
// To read
import java.util.Scanner;
import java.io.FileOutputStream;
// To Write
import java.io.FileReader;
import java.io.PrintWriter;
// For Exception Handling
import java.io.IOException;
```
Then in your main, declare a `FileOutputStream` and `PrintWriter`
```java
FileOutputStream file;
PrintWriter print;
```
### Try-Catch-Finally
Create a try block to open a file for writing
```java
try {
// If the file doesn't exist, it'll create it
file = new FileOutputStream("output.txt");
print = new PrintWriter(file);
} catch (IOException except) {
// Prints out the error message
System.out.println("File error " + except.getMessage());
}
```
Adding a finally block allows the program to clean up before it closes
```java
try {
file = new FileOutputStream("output.txt");
print = new PrintWriter(file);
} catch (IOException except) {
System.out.println("File error " + except.getMessage());
} finally { // It starts here!
delete file;
delete print;
file.close();
return;
}
```
### Write to the file :)
Then you can write the to file!
```java
// Do you notice the following methods?
print.println("Your number is");
print.print("My name is..\n");
print.printf("%s %d", "Hello ", 5);
print.flush(); //Clears the output stream
file.close(); //Closes the file
```
Extra Note: Disk fragmentation is a way of cleaning up memory that isn't being used by any of the code on your computer.
## Swing Graphics
### Importing Necessary Libraries
You need to import all the necessary libraries first
```java
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
```
### Changing the class header
Your class file needs to extend `JFrame` that way it can use a bunch of the already existent code written for Swing applications
```java
public class firstGUi extends JFrame {
//....
```
### Swing Components
Java Swing makes use of what is called Swing Components. These are basic building blocks of GUI items you can add to the screen. For example, a checkbox, a radio button, text field. These are all swing components.
I wrote a blog post back in the summer which is an overview of them. You can check it out here: https://brandonrozek.com/2017/06/java-swing-components/
Inside your `firstGUI` class, declare some Swing components you would like to use in the program
```java
public class firstGUI extends JFrame {
JButton button1;
JTextArea area;
JTextField text;
// ....
```
### Constructor
You need to create a constructor for this class that way you can initiate all of the swing component values.
```java
// ...
JButton button1;
JTextArea area;
JTextField text;
// Begin Constructor
firstGUI() {
// Define the components
JLabel name = new JLabel("Enter in your name:");
text = new JTextField("Jennifer", 20); // 20 characters long, default value: Jennifer
area = new JTextArea(10, 10); //Width and Height is 10 characters big
JScrollPane sp = new JScrollPane(area); //Adds a scroll bar for the text area
button1 = new JButton("Press Me");
// Set the Layout
// FlowLayout organizes each of the components top to bottom, left to right
setLayout(new FlowLayout());
// Add the components to the screen
add(name);
add(text);
add(sp); // never add the textarea when surrounded by a ScrollPane
add(button1);
}
```
### New Main Method
Finally, you need to create the Main method which will initiate it all
```java
public static void main(String[] args) {
firstGUI myFrame = new firstGUI();
// End the program when the 'x' button (not keyboard) is pressed
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("My title"); // Titles the window
myFrame.pack(); // Packs it all into the frame
myFrame.setVisible(true); // Makes the frame appear on the screen
}
```
### Making it interactive
You need to change your class header to the following
```java
public class firstGUI extends JFrame implements ActionListener {
// ...
```
Then in your class, add the following method
```java
@Override public void actionPerformed(ActionEvent event) {
// Do stuff as a result of an event here
area.append("You Pressed the Button");
}
```
To make it actually activate as a result of an event. You need to attach it to a swing component.
For example, I want the code in `actionPerformed` to activate in result of a button press.
Add the following line to your code in the constructor.
```java
//...
button1 = new JButton("Press Me");
button1.addActionListener(this); // New Code
//....
```
### Identifying Button Pressed
How do you know which button was pressed in the `actionPerformed` method?
You can use `event.getSource()` to find out.
Example:
```java
@Override public void actionPerformed(ActionEvent event) {
if (event.getSource() == button1) { // Replace button1 with appropriate variable name
// Do things as a result of a specific button being pressed
}
}
```
### Summary
To use Swing, do the following steps
1. Import Libraries
2. Declare J___ variables
3. New the J___ variables
4. Add the J___ variables to the frame
5. Add the `ActionListener` to the components you wish to monitor

View file

@ -0,0 +1,109 @@
# Lecture Notes for November 15th
Import the necessary libraries
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
```
This time we'll be using the null layout. This will require you to set the x, and y positions of each of the elements on the screen
First we'll make a class called `GUILayout` which will extend `JPanel` and contain our layout and components
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUILayout extends JPanel {
private JButton one, two;
private JTextField text;
private JTextArea area;
private int count; // Used to keep track of button pushes
private int number = 0;
GUILayout() {
// Set the layout to the null layout
setLayout(null);
// Tells the computer that you wish to have the size of your program to be 500x500
setPreferredSize(new Dimension(500, 500));
// Create the buttons
one = new JButton("Change color");
two = new JButton("Count Pushes");
// Set the x, y, width, height inside parenthesis
// This places the buttons on the specified locations on the screen
one.setBounds(10, 10, 100, 24);
two.setBounds(120, 10, 100, 24);
// Sets the color of the text of button 1 to blue
one.setForeground(Color.BLUE);
// Add the components to the screen
add(one);
add(two);
text = new JTextField("Today is Wednesday, a photographer is here.");
text.setBounds(10, 40 ,480, 24);
add(text);
area = new JTextArea(20, 20);
// Wrap the text area into the scroll pane
// This adds the scroll bars (vertical/horizontal)
JScrollPane sp = new JScrollPane(area);
sp.setBounds(10, 75, 490, 400);
add(sp);
// Bind the Listener class to the button one
one.addActionListener(new Listener());
// Bind it to two and text
two.addActionListener(new Listener());
text.addActionListener(new Listener());
}
// Create the class for the listener
private class Listener implements ActionListener {
// Define what you want to occur after an event
public void actionPerformed(ActionEvent event) {
if (event.getSource() == one) {
} else if (event.getSource() == two) {
count++;
// \n is needed to prevent scrolling
area.append("You pressed the button " + count + " times!");
} else if (event.getSource() == text) {
// Grab the number inside the text area and set it to the variable number
number = Integer.paseInt(text.getText());
number += 10;
// add "" to number so that it converts number to a String
text.setText(number + "");
// Convert the number to a String
String temp = Integer.toString(number);
area.setText(temp);
}
}
}
}
```
The main code is really short, you just need to extend `JFrame` and some short code seen last class to set it up.
```java
public class mainTester extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Sample GUI"); // Sets the title to "Sample GUI"
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Instantiate the GUILayout file you made before
frame.getContentPane().add(new GUILayout());
}
}
```

View file

@ -0,0 +1,116 @@
# Lecture for November 20
## Adding a drawing panel to the GUI
You can't put swing and graphics together, therefore you need to make a seperate JPanels for swing and graphics.
Add necessary libraries
```java
import java.awt.*;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
```
```java
public class drawingWindow extends JPanel {
JTextField field;
JButton draw;
DrawingPanel drawingPanel;
public drawingWindow() {
// Each new component would be vertically stacked upon each other
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel swingSTuff = new JPanel();
// Add things to the screen
draw = new JButton("Draw");
field = new JTextField();
swingStuff.add(field);
swingStuff.add(draw)
// Add the drawing panel onto the screen
drawingPanel = new DrawingPanel(200, 400);
add(drawingPanel);
// Activate the listener if the button was pressed
draw.addActionListener(new Listener());
}
// Add the listener to respond to events
private class listener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == draw) {
drawingPanel.setFlag(1);
// Repaints the screen so the oval can appear
drawingPanel.repaint();
}
}
}
// Create the draw panel so we can add it to the screen
private class DrawingPanel extends JPanel {
private int width, height;
DrawingPanel(int width, int height) {
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width, height));
}
public void setFlag(int flag) {
this.flag = flag;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Every time the flag is set, draw an oval at a random location and color
if (flag == 1) {
Random rand = new Random();
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.setColor(Color.RED);
g.fillOval(x, y, 20, 30);
}
}
}
}
```
There are a myriad of different methods you can use.
```java
// Assume width, height, y, x, etc are defined above
public void paintComponent(Graphics g) {
//....
g.dispose(); // Flushes the graphics buffer
}
```
You have the traditional fill and draw methods. Fill creates the shape shaded in with a color. Draw creates an outline of the shape.
```java
// ...
g.fillRect(x ,y, width, height);
g.drawRect(x, y, width, height);
g.fillOval(x, y, width, height);
g.drawOval(x, y, width, height);
//g.drawPoly(parematers...);
//g.fillPoly(parameters...);
g.drawArc(x, y, width, height, startingAngle, sweepingAngle);
g.fillArc(x, y, width, height, startingAngle, sweepingAngle);
```
You can also create complex shapes like a polygon. When adding points, you need to make sure you add them Clockwise or Counterclockwise (but NOT both)
```java
Polygon tri = new Polygon();
tri.addPoint(150, 10);
tri.addPoint(175, 100);
tri.addPoint(125, 100);
// Add points clockwise or counterclockwise (NOT BOTH)
```

View file

@ -0,0 +1,267 @@
# Lecture for November 27
## Recursion
When doing recursion, make sure not to use loops.
Recursion is when a function makes a function call to itself.
It consists of two parts:
- Base Case: This tell it when to stop
- Smaller Caller Case: Helps you get closer to the base case
You can have one or more base cases or caller cases.
To teach recursion, we'll start with a problem that should be written iteratively (with loops) but we'll show how to do it with recursion.
### Example: Counting Down
```java
void CountDown(int number) {
while (number > 0) {
System.out.println(number + " ");
number = number - 1;
}
System.out.println("Blast Off")
}
```
1. How does this loop stop? -- Base Case
2. How does this loop change each time through? -- Smaller caller case
Base Case: It stops when the number equals 0
```java
// Base Case
if (number == 0) {
System.out.println("Blast Off");
return;
}
```
Smaller Caller Case: It decreases number by 1
```java
// Smaller Caller Case
System.out.print(number + " ");
countDownRecursive(number - 1);
```
Put it together...
```java
void countDownRecursive(int number) {
if (number == 0) {
System.out.println("Blast Off");
} else {
System.out.print(number + " ");
countDownRecursive(number - 1);
}
}
```
Prints `10 9 8 7 6 5 4 3 2 1 Blast Off`
### Stack Snapshots
Every time you make a recursive call, it keeps track of all the local variables at the current function call and pushes it onto the stack.
That means if you make 10 recursive calls, you'll have 10 slots added onto the stack. If you want to return back to the beginning, you would need to return 10 times.
### Order Matters
Whether you do the recursive step first or some other action, it completely changes the output. Look at the following example that's similar to `countDownRecursive`.
```java
void countUpRecursive(int number) {
if (number == 0) {
System.out.println("Blast Off");
} else {
// Notice the swapping of the next two lines
countUpRecursive(number - 1);
System.out.print(number + " ");
}
}
```
This would print out `Blast Off 1 2 3 4 5 6 7 8 9 10`
### Example: Summing up to a number
This would be our iterative solution
```java
int sum(int number) {
int sum = 0;
while (number > 0) {
sum += number;
number--;
}
return sum;
}
```
How does this loop stop?
Same as before. Think about it, if the number you pass in is zero, what should be the result of sum? Zero. Since adding up from 0 to 0 is just 0.
```java
if (number == 0) {
return 0;
}
```
How does this loop change each time through?
You want to update your sum, so return the sum of the next call to the current sum.
```java
return (number + sum(number - 1));
```
Putting it all together
```java
int sumRecursive(int number) {
if (number == 0) {
return 0;
} else {
return number + sumRecursive(number - 1);
}
}
```
### Example: Linear Search
How to do it iteratively.
```java
void linearSearch(int[] array, int number) {
int i = 0;
while (i < array.length && number != array[i]) {
i++;
}
if (i == array.length) {
System.out.println("Not Found");
} else {
System.out.println("Found");
}
}
```
Base Case: There are two base cases, when it reaches the end of the array and when it finds the number
```java
if (array.length == i) {
System.out.println("Not Found");
} else (array[i] == number) {
System.out.println(number + " found at index " + i);
}
```
Smaller Caller Case: Check the next element
```java
linearSearchRecursion(number, array, i + 1);
```
Putting it all together...
```java
void linearSearchRecursion(int[] array, int number) {
if (array.length == i) {
System.out.println("Not Found");
} else if (array[i] == number) {
System.out.println(number + " found at index " + index);
} else {
linearSearchRecursion(number, array, i + 1);
}
}
```
## Binary Search
This is a much more efficient search than the linear search we have been doing. The only condition is that your array must be sorted beforehand.
A regular linear search `O(n)` -- Check at most all of the elements of the array.
Binary Search `O(log(n))` -- Checks at most `ceil(log(n))` elements of an array.
To demonstrate this with real numbers, let's take an array of 100 elements
- With linear search this will take at most 100 iterations
- With binary search this will take at most **7**.
Crazy right?
### Implementation
**Iterative approach**
```java
void binarySearch(int number, int[] array) {
int lower = 0;
int upper = array.length - 1;
int mid = (lower + upper) / 2
while (lower <= upper && array[mid] != number) {
mid = (lower + upper) / 2;
if (array[mid] < number) {
lower = mid + 1;
} else if () {
upper = mid -1;
}
}
if (lower > upper) {
System.out.println("Not Found");
} else {
System.out.println(number + " found at index " + mid);
}
}
```
**Recursive Approach**
Base Case: There are two cases, you either found it, or you made it to the end of the array without finding it
```java
if (lower > upper) {
System.out.println("Not Found");
} else if (array[mid] == number) {
System.out.println(number + " found at index " + mid);
}
```
Smaller Caller Case: Change the lower or upper bounds to cut the search in half
```java
if (array[mid] < number) {
lower = mid + 1;
binarySearchRecursive(number, array, lower, upper);
} else if (array[mid] > number) {
upper = mid - 1;
binarySearchRecursive(number, array, lower, upper);
}
```
Putting it together....
```java
binarySearch(int number, int[] array, int lower, int upper) {
if (lower > upper) {
System.out.println("Not Found");
} else if (array[mid] == number) {
System.out.println(number + " found at index " + mid);
}
else if (array[mid] < number) {
lower = mid + 1;
binarySearchRecursive(number, array, lower, upper);
} else if (array[mid] > number) {
upper = mid - 1;
binarySearchRecursive(number, array, lower, upper);
}
}
```

View file

@ -0,0 +1,137 @@
# November 6th Lecture
## Compare cont.
Continuing from last week's topic, writing a function called `compare` in your custom class.
For example, for your project:
```java
public bool compare(ResearchProject right, int type) {
if (type == 0) { // Is last lastname greater than right lastname alphabeticallly
if (lastname.compareTo(right.lastname) > 0) {
return true;
} else {
return false;
}
} else if (type == 1) { // Implement a different type of comparison
}
}
```
You can then use the sorting algorithms discussed previously to sort the ResearchProjects using the `compare` method.
## File IO
First start by importing the required libraries.
```java
import java.io.FileInputStream;
import java.io.IOException; // For error handling
import java.io.FileNotFoundException; // For error handling
import java.util.Scanner;
```
Then inside your main method which throws an IOException (see example "Reading the filename from the keyboard")
```java
FileStream file;
Scanner in;
try { // Try something
file = new FileInputStream("test.txt");
in = new Scanner(file);
} catch (FileNotFoundException e) { // Catch IF it fails
System.out.println("File not found.");
in = new Scanner(System.in); // Read from the keyboard instead
}
// Read the file now....
String name = in.nextLine();
```
Before we had linked the Scanner to the keyboard, now we're doing it to a file.
### Try-Catch
In the code above you see what's called a try-catch block. That means that if something was to happen in the execution of the code. Instead of just crashing as we have been seeing normally. We can deal with the error. In the example above you saw that the program reads from the keyboard instead of the file
### Reading the filename from the keyboard
```java
public static void main(String[] args) throws IOException {
FileInputStream file;
Scanner in, scnr;
// Connect one scanner to the keyboard to get the filename
scnr = new Scanner(System.in);
System.out.print("Enter file name: ");
String filename = in.nextLine();
// Repeat code from previous example
FileStream file;
Scanner in;
try {
file = new FileInputStream(filename); // Only this line changed
in = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
in = new Scanner(System.in);
}
String name = in.nextLine();
// ....
}
```
The main throws the IOException since we don't deal with it in any of the catch blocks.
### Reading names of people from a file into an array
Let's say we have a file with the following in it
```
3
Paul
Peter
Mary
```
3 is to indicate the number of names in th file.
Let's write code in order to read these names into an array!
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
public static void main(String[] args) throws IOException {
FileInputStream file;
Scanner in, scnr;
scnr = new Scanner(System.in);
System.out.print("Enter file name: ");
String filename = in.nextLine();
FileStream file;
Scanner in;
try {
file = new FileInputStream(filename); // Only this line changed
in = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
in = new Scanner(System.in);
}
// For the size of the array, get the first number in the file
int size = in.nextInt();
String[] nameArray = new String[size];
for (int i = 0; i < size; i++) {
namesArray[i] = in.nextLine();
}
// Now all the names in the file is in the namesArray
}
```

View file

@ -0,0 +1,133 @@
# Lecture Notes October 11
## Global Variables
Global variables is where you don't declare a variable inside a method. This is generally not a recommended practice. It is recommended to declare variables inside methods so that it is easier to reuse code.
```java
public class mainDriver {
public static int globalVariable = 5; // I am a global variable
public static void main(String[] args) {
int localVariable = 4; // I am a local variable
}
}
```
## String Formatting
You can format strings in java by using the `printf` method in System.out.
Format strings work by using placeholders starting with `%` to specify where to place the value of a variable.
General format of command
```java
//System.out.printf(FormatString, variable1, variable2, ....)
String s = "The number is";
int x = 5;
System.out.printf("%s %d", s, x); // Prints "The number is 5"
```
If you want to print out money, you can do it through the following
```java
float tax = 0.45698;
System.out.printf("The tax is %.2f"); //prints "The tax is 0.46"
```
## Floating point precision
Due to how computers store non-integers, math can be non-precise after some mathematical operations. It is therefore advantageous to do operations on integers to the level of precision you want.
For example, instead of working in dollars, work in pennies since it's the smallest division we care about.
### ArrayList
Standard arrays are static, meaning they have no ability to grow. Instead of doing the operations we described last class, in order to add something to an array. We can use something called an `ArrayList` instead.
The methods in the `ArrayList` library are useful abstractions to make the life of a programmer easier.
ArrayLists can also hold only one type. The type cannot be a primitive like a standard array. Instead it must be a class representing the desired type.
int -> Integer
double -> Double
char -> Character
float -> String
To declare and initialize an `ArrayList`
```java
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
}
}
```
`ArrayList`s has a variety of different methods that can be used to access/manipulate it
- get
- set
- add
- clone
- clear
- size
If you want to add the numbers 1 through 10 into the `ArrayList` of numbers
```java
for (int i = 1; i < 11; i++) {
numbers.add(i);
}
```
To print out the entire contents of the `ArrayList`
```java
for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i));
}
```
How can you replace a value?
```java
int n = 5; // Make this the number you wish to replace
int i = 0;
while (i < numbers.size() && numbers.get(i) != n) {
i++;
}
if (i == numbers.size()) {
System.out.println(n + " not found.");
} else {
int r = 10; // Make this the value you want to replace n with
numbers.set(i, r);
}
```
The `remove` method removes an item given an index. This shifts all the elements above the removed index down.
```java
numbers.remove(3); // Removes the element in the third index
```
The `add` method can also take an index. It pushes all the elements at the index specified up.
```java
numbers.add(3, 5); // Adds the number 5 to the third index
```
You can clone an array using the `clone` method
```java
ArrayList<Integer> numbers2 = new ArrayList<Integer>();
numbers2.clone(numbers); // Clones numbers into numbers2
```

View file

@ -0,0 +1,75 @@
# October 18th
## ArrayLists in classes
```java
public class Numbers {
private ArrayList<Integer> used;
private ArrayList<Integer> unused;
numbers () {
// Debug: System.out.println("1. Constructor Entry Point");
used = new ArrayList<Integer>();
unused = new ArrayList<Integer>();
// Debug: System.out.println("2, Constructor Size of ArrayLists" + used.size() + " " + unused.size())
}
// Adds the numbers 1-5 into the used ArrayList
public void fillUsedArrayList() {
for (int i = 0; i < 5; i++) {
used.add(i + 1);
}
}
// Move an item from the unused ArrayList to the used ArrayList
public int moveIt(int index) {
int temp = used.get(index);
unused.add(temp);
// Debug: System.out.println("Adding to used array:" + (i + 1));
used.remove(index);
return temp;
}
// The method below is created for debugging purposes
public void printBothArrayLists() {
// Print the used arraylist
System.out.println("Used ArrayList");
for (int i = 0; i < used.size(); i++) {
System.out.println(used.get(i));
}
// Print the unused arraylist
System.out.println("Unused ArrayList");
for (int i = 0; i < unused.size(); i ++) {
System.out.println(unused.get(i));
}
}
}
```
Recall that you can compile the code above but you cannot run it. To run code, you must have a main method.
## NumberTester
```java
public class NumberTester {
public static void main(String[] args) {
Numbers list;
list = new Numbers();
list.fillUsedArrayList();
list.printBothArrayLists();
}
}
```
## Difference between Array and ArrayList
An Array is a **static** structure of contiguous memory of a single type.
An ArrayList is a **dynamic** structure of contiguous memory of a single type
To get the size of an array you use `.length`
To get the size of an ArrayList you use `.size()`

View file

@ -0,0 +1,160 @@
# Lecture Notes Oct 2nd
## Array
`array` is not a reserved word, it's a concept. Arrays are able to hold multiple values under one name of the same type.
For instance, you can have an array of integers.
Properties of an array
- Size (n)
- index [0, n - 1]
You can declare arrays by saying the type '[]' and the name of the array
```java
int[] numbers;
double[] gpas;
float[] grades;
```
Before you can use the array, you must `new` it
```java
numbers = new int[10];
```
Where 10 is the size of the array.
You can combine both the declaration and initialization
```java
double[] points = new double[7];
```
You can access individual elements of the array by using its index. Indexes start from zero
```java
points[0] = 5.4; // The first element in the point array is 5.4
```
The `.length` property of an array gives the size of the array
## For-Loops + Arrays
You can print out each element in the array using a for loop
```java
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
```
You can ask a user to input a value to each element in the array
```java
for (int i = 0; i < points.length; i++) {
System.out.print("Enter a number: ");
points[i] = scnr.nextInt();
}
```
## While-Loops + Arrays
You can use a while loop to search the array
```java
int i = 0;
int number = 5;
// While the index is within the array size and the number isn't found
while (i != number.length && number != numbers[i]) {
i++
}
if (i == numbers.length) {
System.out.println(number + " was not found.")
} else {
System.out.println(number + " was found at index " + i)
}
```
If you don't include the `i != number.length` you will obtain an `IndexOutOfBounds` error.
The example above is called a *Linear Search*.
Linear searches work on an unsorted and sorted arrays.
## Methods + Arrays
You can pass an array into a method
```java
public static void exampleMethod(int[] sample) {
// Do something
}
public static void main(String[] args) {
int[] s = new int[30];
exampleMethod(s);
}
```
## Do-While Loops
For-loops can run 0 or more times. If you want something to execute at least once. Use a do-while loop.
```java
do {
// Code
} while (condition);
```
For example, to search at least once and asking whether the user wants to search again
```java
// Assume linearSearch and array are defined
char answer;
Scanner input = new Scanner(System.in);
do {
linearSearch(array, input);
System.out.print("Do you want to search again? (Y/N) ");
input.nextLine();
answer = input.next().charAt(0);
} while( answer != 'N');
```
You can create any type of loop just by using a while loop.
## Example: Finding the Max
You can find the max of an array using the following method
```java
double max = arrayName[0];
for (int i = 1; i < arrayName.length; i++) {
if (max < arrayName[i]) {
max = arrayName[i];
}
}
System.out.println("The max is " + max);
```
## Example: Summing up an array
You can sum the array using the following method
```java
double sum = 0;
for (int i = 0; i < arrayName.length; i++) {
sum += arrayName[i];
}
System.out.println("The sum is " + sum);
```

View file

@ -0,0 +1,78 @@
# Lecture for October 23
## Two-Dimensional Arrays
You can think of a two dimensional array as a grid that is organized by rows then columns.
To declare a two dimensional array do the following
```java
int[][] grid = new int[5][5]; // Declares a 2D array of 5 rows and 5 columns
```
You can have as many dimensions as you want. For graphics a 3-dimensional array would render 3D points.
It doesn't have to be inherently visual though, you can have the n-dimensional array look at the interaction between n different variables. For example, the relationships to different questions in a survey.
Strings are essentially a char array with extra methods attached. We can imitate an array of strings with a 2D char array.
```java
char[][] helloWorld = new char[5][5];
hello[0][0] = 'h';
hello[0][1] = 'e';
hello[0][2] = 'l';
hello[0][3] = 'l';
hello[0][4] = 'o';
hello[1][0] = 'w';
hello[1][1] = 'o';
hello[1][2] = 'r';
hello[1][3] = 'l';
hello[1][4] = 'd';
```
## Nested-For Loops
To access the elements in a 2D array, you need to use a nested for-loop.
Here is how you print out the hello world example above
```java
for (int row = 0; row < helloWorld.length; row++) {
for (int col = 0; col < helloWorld[row].length; col++) {
System.out.print(helloWorld[row][col]);
}
System.out.print(" ")
}
```
The code above prints out "hello world"
## 2D Arrays in methods
You can write a get like method in the following way
```java
public static void get(int[][] array, int row, int col) {
return array[row][col];
}
```
Arrays in Java are pass by reference not pass by value. Meaning that if you change the array within the method then it will change outside the method.
```java
public static void insert(int[][] array, int row, int col, int numToInsert) {
array[row][col] = numToInsert;
}
```
To make it not be able to change the array inside the method, use the keyword `const` inside the method header. To code below will throw a compiler error.
```java
public static void insert(const int[][] array, int row, int col, int numToInsert) {
array[row][col] = numToInsert; // This line will throw an errror
}
```

View file

@ -0,0 +1,21 @@
# Lecture on Oct 25
## 2 Dimension Array of Objects
You can not only do a two dimensional array of primitive types, but you can also do two dimensional arrays of objects/classes.
```java
animalLocation[][] map;
map = new animalLocation[5][4];
```
Since we are dealing with classes, you cannot use this array right away. The code above creates the space in memory to store the objects. To have the animalLocation objects in the array, you must `new` each instance of the object.
```java
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = new animalLocation();
}
}
```

View file

@ -0,0 +1,101 @@
# Oct 30 Lecture
## Sorting
### Bubble Sort
These instructions are to sort in descending order, to sort in ascending order just negate the condition.
This sort is a series of iterations, for each iteration you go to the bottom of the array. Then compare if the value is greater than the element before it. If it is, then you
1. Go to the bottom of the array
2. Compare the value to the one before it
1. If it's greater than the element before it -> swap
3. Move on to the value before it and repeat step 2.
Once you go through an iteration, the last thing being compared is the greatest value of the entire array. That means you don't have to check it every time anymore.
Keep going through all the iterations until n, where n is the size of the array, iterations have been completed.
### Swapping Values
If you try to swap variables by saying
```java
y = x;
x = y;
```
then you'll end up overwriting y's value with x and both variable would have x's value.
If you want to actually swap variables, you must create a temporary variable that saves y's value so that it can be properly assigned to x.
```java
int temp;
temp = y;
y = x;
x = temp;
```
### Implementation (Not Complete)
```java
// Each iteration
for (int j = 0; j < array.length - 1; j++) {
// Each element in the list
for (int i = 0; i < array.length - 1; i++) {
// Is the element greater than the one after it?
if (array[i] > array[i + 1]) {
// Swap
int temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
```
This here compares each of the values each time. If you remember before, I said that you don't have to compare the topmost each time.
### Implementation
To change this, just change the second loop condition
```java
// Each iteration
for (int j = 0; j < array.length - 1; j++) {
// Each element in the list
for (int i = 0; i < array.length - 1 - i; i++) { // Note this line
// Is the element greater than the one after it?
if (array[i] > array[i + 1]) {
// Swap
int temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
```
## Compare
In Java, you can compare numbers, strings, and even your own customized objects. To compare your own customize object, you must write a method called `compare` in your class.
### To use your compare method in the sorting algorithm
```java
// Each iteration
for (int j = 0; j < array.length - 1; j++) {
// Each element in the list
for (int i = 0; i < array.length - 1 - i; i++) {
// Is the element greater than the one after it?
if (array[i].compare(array[i + 1])) { // Note this line
// Swap
int temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
```

View file

@ -0,0 +1,30 @@
# Lecture on October 4th
## Pass by Copy vs Pass by Reference
### Pass by Copy
When you pass a primitive type into a method (int, char, double, float, etc), it makes a copy of the value of the variable and brings it into the method
### Pass by Reference
When you pass an array into a method (int[], char[], double[], etc[]), it passes in the reference of the variable into the method. In other words, you give the actual array into the method and allows the method to change it.
### What's the Implication?
If you change the primitive in a method, it doesn't actually change the value of the variable.
If you pass in an array and change it in the method, it has been permanently changed outside the method as well.
### How do I make it so I can't change my array by accident?
Use the `final`keyword in the method header
```java
public static void printAll(final int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("Number " + (i + 1) + " is " + array[i])
}
}
```

View file

@ -0,0 +1,37 @@
# Lecture Notes October 9th
## Arrays (Cont.)
### Another way of Array Initialization
```java
String[] names = {"Jennifer", "Noodle", "Fluffy", "Rosie", "Cinnamon", "Brianne", "Oliver"}
```
Everything between the `{}` is the initial values in the names array in the order that it is written.
Recall that arrays are of a fixed size. The `names` array above has 7 elements.
### What can I do if I want to add something to the names array?
Do the following steps:
1. Create an empty array with the same size as the array
2. Take all the contents in the array and store it in a temporary array
3. Set names equal to another array of a bigger size
4. Take all the contents in temp and store it back to the array of choice
5. Add an element to the array by index
```java
// (1)
String[] temp = new String[7];
// (2)
temp.clone(names);
// (3)
names = new String[20]; // Now it can hold up to 20 names
// (4)
names.clone(temp);
// (5)
names[7] = "New name!";
```

View file

@ -0,0 +1,220 @@
# CPSC 220 Lecture 4
## Practice Problem
1. Create a class called Car
2. - Create a private variable of int type called year
- Create a private variable of String type called make
3. Create accessor methods for all data members.
4. Create mutator methods for all data methods.
```java
public class car { // begin car
private int year;
private String make;
public int getYear(void) {
return year;
}
public String getMake() {
return make;
}
public void setYear(int y) {
if (y > 1890) {
year = y;
} else {
System.out.println(y + " is not a valid year.");
}
}
public void setMake(String m) {
make = m;
}
}
```
Local variables are only existent within the curly braces that it is defined in.
## If Statements and Boolean Expressions
Boolean expressions return a boolean
```java
1 < 4; // 1 is less than 4: TRUE
3 > 5; // 3 is greater than 5: FALSE
5 == 5; // 5 is equal to 5: TRUE
5 != 5; // 5 is not equal to 5: FALSE
1 >= 1; // 1 is greater than or equal to 1: TRUE
5 <= 1; // 5 is less than or equal to 1: FALSE
```
If statements only occur if the boolean expression is true, otherwise the `else` block is executed.
```java
if (true) {
System.out.println("I am always printed");
} else {
System.out.println("I am never printed");
}
```
You can only have one `else` per `if`. If you have an `if` you don't necessarily need an `else`
## Local vs Class Variables
If you have a local variable and the class variable sharing the same name, then the local variable is always used first.
```java
public class car { // begin car
private int year;
public void setYear(int year) {
year = year;
}
}
```
This is a redundant statement, it makes the argument that is passed in equal to itself.
To avoid this situation, use the keyword `this` to access the class variable
```java
public class car {
private int year;  
public void setYear(int year) {    
this.year = year;
}
}
```
The code above runs as expected.
Rewriting our class with `this`
```java
public class car { // begin car
private int year;
private String make;
public int getYear(void) {
return year;
}
public String getMake() {
return make;
}
public void setYear(int year) {
if (y > 1890) {
this.year = year;
} else {
System.out.println(y + " is not a valid year.");
}
}
public void setMake(String make) {
this.make = make;
}
}
```
## Unreachable Code
When the code hits a `return` statement, it stops executing the rest of the code in the method. Also throws an Unreachable Code Error.
```java
public int add(int x, int y) {
return x + y;
System.out.println("x + y = " + x + y);
}
add();
System.out.println("Hello");
```
Here the code above will not compile, though assuming the error doesn't exist then it would only print out "Hello"
## Constructors
You cannot have a private or protected constructors.
Constructors are used to initialize your objects.
You want to have the class variables to the left of the assignment statement.
```java
public class car {
private int year;
private String make;
car() {
year = 1890;
make = "Ford";
}
car(int year, String make) {
this.year = year;
this.make = make;
}
}
```
## Testers
Testers are useful to check that the class is implemented correctly. Both the tester and the class have to be in the same folder/directory.
```java
public class carTester {
public static void main(String[] args) {
Car myCar; // Declaration
myCar = new Car(); // Initilization
Car yourCar = new Car(2009, "Hyundai"); // Declaration + Initialization
}
}
```
## More about classes
```java
public class Car {
private String name;
private int odometer;
public void setOdometer(int od) {
odometer = od;
}
public void setName(String n) {
this.name = n;
}
public void changeOilRequest(String name, int od) {
if (name == this.name) {
int difference = od - this.odometer;
if (difference > = 3000) {
// You can call other methods in the class
setOdo(od); // Equivalent to "this.setOdo(od);"
this.odometer = od;
System.out.println("Ready for oil change.");
} else {
System.out.println(name + " not ready for oil change.")
}
} // end if
} // end changeOil request
} // end class
```
To call public methods outside the class use the variable name to do so.
```java
public class CarTester {
public static void main(String[] args) {
Car myCar = new Car();
myCar.setName("Honda")
myCar.changeOilRequest("Honda", 3400);
}
}
```
## Math library
The `ceil` method rounds up while the `floor` method runs down.
```java
Math.ceil(3.2); // 4
Math.ceil(4.1); // 4
```

View file

@ -0,0 +1,177 @@
## Counting Loop
Looking at the following example code
```java
int i;
for (i = 0; i < 3; i++) { //begin for
System.out.println("i = " + i); //body
} //end for
System.out.println("After loop, i = " + i);
```
`i = 0` is the initializing statement
`i < 3` is the conditional, that is when the loop ends
`i++` is the increment/decrement
`i++` is synonymous with `i = i + 1`
The initialization statement only occurs once at the beginning of the loop.
### Execution Example
Let us go through this for loop example
- Let us set `i = 0`
- Is `i < 3`? Yes execute the body
- The body executes an output of `"i = 0"`
- Now we increment `i ++`, i is now 1
- Is `i < 3`? Yes, 1 is less than 3. Execute body
- The computer prints out `"i = 1"`
- Increment `i++` i is now 2
- Is `i < 3`? Yes 2 is less than 3. Execute body
- The computer prints out `"i = 2"`
- Increment `i++`, i is now 3
- Is `i < 3`? No 3 is not less than 3
- Don't execute body of loop
Exit loop. Print `"After loop, i = 3"`
### Condensing Syntax
You can also do the declaration in the initialization statement
```java
for (int i = 0; i < 3; i++) {
System.out.println("i = " + i);
}
```
This now runs like above without the `"After loop, i = 3"` print. You cannot access the variable `i` outside the for loop since in this example, it belongs to the for loop's scope.
## Logic Expressions
### And Statements
With the AND operator `&&` both the left and right side needs to be true for the expression to be true.
```java
true && true // true
true && false // false
false && true // false
false && false // false
```
### Or Statements
With the OR operator `||` either the left or right side needs to be true for the expression to be true.
```java
true || true // true
true || false // true
false || true // true
false || false // false
```
### Examples
**Example**: Print out the number `n` if it is between 10 and 20 (inclusive)
```java
if (n >= 10 && n <= 20) {
System.out.println(n);
}
```
**Example**: Print out the `age` if it is not of young adult age. Young adult range is from 18 to 39 (inclusive)
```java
if (!(age >= 18 && age <= 39)) {
System.out.println(age);
}
```
Or you can use De Morgan's Law (for the curious)
```java
if (age < 18 || age > 39) {
System.out.println(age);
}
```
## For Loops (Cont.)
### Backwards counting
You can use the loop to count backwards
```java
for (int i = 10; i > -1; i--) {
System.out.println(i);
}
```
This prints the following
```java
10
9
8
7
6
5
4
3
2
0
```
### Rows-Columns
You can make rows and columns of asterisks
```java
for (int j = 0; j < someNumber; j++) { // Corresponds to rows
for (int i = 0; i < someNumber2; i++) { // Corresponds to columns
System.out.print("*");
}
System.out.println(""); // Goes to the next row
}
```
If `someNumber` equals `someNumber2`, then we have the same amount of rows as columns.
Let `someNumber` equal to 2 and `someNumber2` equal to 2
Output:
```
**
**
```
### Right Triangles
You can make a right triangle of Tilda with the following code
```java
for (int i = 1; i <= num; i++) { // Corresponds to the row
for (int j = 0; j < i; j++) { // Corresponds to the column and stops at the current row number
System.out.print("~");
}
System.out.println(""); // Moves to next row
}
```
##### What are for-loops used for? *Reusing code*

View file

@ -0,0 +1,97 @@
# Lecture in CPSC 220 Sept 25 2017
## Constants
Adding the keyword `final` in front of a variable declaration makes the variable constant. Meaning you cannot later change it in the code.
```java
final int MAX = 10;
```
By industry norm, the style of the variable is to have it in all caps.
You CANNOT do the following
```java
final int MAX = 10;
MAX = 15;
```
## Using Libraries
1. Import the library
2. Find the method that is appropriate
3. Use it
Example:
```java
import java.util.Math;
public class MathTest {
public static void main(String[] args) {
double answer = Math.ceil(5.4);
System.out.println(Math.ceil(4.5));
}
}
```
## Typecasting / Type Conversions
You can only cast a variable if you are casting it to a type that is larger than the one it was previously. The expression Polack used is that you cannot fit into super skinny jeans, but you can fit into bigger pants.
```java
double dnum;
float fnum;
int inum;
dnum = (double)fnum * (double)inum;
```
## Char vs String
`String`s are initialized in Java with double quotes while `char`s are initialized with single quotes
```java
char initial = 'j';
String name = "Jennifer";
```
Characters can be read in as an integer.
## Random Numbers
1. Import `java.util.Random;`
2. Declare the random number generator
3. Initialize with `new`
4. Use it
```java
import java.util.Random;
public class RandTest {
public static void main(String[] args) {
Random rand;
rand = new Random();
int number = rand.nextInt(100); // Random generates number between 0-99
}
}
```
How do you generate numbers in a different range? [50, 150]
```java
rand.nextInt(100); // 0-99
rand.nextInt(101) // 0 - 100
rand.nextInt(101) + 50 //50-150
```
In more general terms
```java
rand.nextInt(end - start + 1) + start
```

View file

@ -0,0 +1,298 @@
# CPSC 220 Lecture 3
## Variables
Variable -- Storage of information
The type cannot change in a variable.
Examples of types include
- int
- float
- double
- String
- char
- boolean
Declaration: `int num;`
Initialization: `num = 5;`
Declaration + Initialization: `int num = 5;`
### Possible Errors
**You cannot declare a variable multiple times.**
Undefined variables are when you do not declare a variable before attempting to use it.
### Casting
You need to cast if you are attempting to lose data or store a larger memory type into a smaller one.
double -> float -> int **(casting required)**
```java
double gpa = 3.2;
int num1 = 10 * (int)gpa // 30
```
# Operations
The basic number operations are
- +
- -
- *
- /
- % *(the remainder)*
Examples
```java
0 % 2 // 0
1 % 2 // 1
2 % 2 // 0
3 % 2 // 1
4 % 2 // 0
5 % 2 // 1
3 % 5 // 3
7 % 5 // 2
```
You can test if something is even using modulus %
```java
// Assuming i was initiliazed to a value earlier
if (i % 2 == 0) {
System.out.println("i is even");
} else {
System.out.println("i is odd");
}
```
# System input
Here is sample code using a Scanner as input
```java
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner in;
in = new Scanner(System.in);
// Grab numerical values
int num = in.nextInt();
float gpa = in.nextFloat();
double weight = in.nextDouble();
// Grab a single character
in.nextLine()
char initial = in.next().charAt(0);
// To get the entire line of a string
in.nextLine();
String name = in.nextLine();
}
}
```
You need to use `in.nextLine()` to grab the carriage return that is left after grabbing a numeric value.
# Classes and Objects
Classes are a new type that you can have multiple things of.
These classes are blueprints that are made up of primitives or more basic types.
First create a Pet.java file (Name of the class must match the name of the file)
```java
public class Pet {
private String name;
private int years;
}
```
You can then use the Pet class in your main program. The terminology here is that you can create instances or objects of the class.
In PetTester.java
```java
public class PetTester {
public static void main(String[] args) {
Pet myPet;
myPet = new Pet();
}
}
```
**Both Pet.java and PetTester.java must be in the same directory/folder**
### Mutators/Accessors
Since the variables are private we cannot access them in the main program. To work around this, we can write what is called a mutator method.
```java
public class Pet {
private String name;
private int years;
// Mutators
public void setName(String n) {
name = n;
}
public void setYears(int y) {
if (y >= 0) {
years = y;
} else {
System.out.println("No one is less than 0 years old.")
}
}
}
```
Now let's use these new methods
```java
public class PetTester {
public static void main(String[] args) {
Pet mypet;
myPet = new Pet();
myPet.setName("Fred");
myPet.setAge(20);
}
}
```
We need a method that will allow us to access the data type. Let's add accessors to our pet class.
```java
public class Pet {
private String name;
private int years;
// Mutators
public void setName(String n) {
name = n;
}
public void setYears(int y) {
if (y >= 0) {
years = y;
} else {
System.out.println("No one is less than 0 years old.")
}
}
// Accessors
public String getName() {
return name;
}
public int getYears() {
return years;
}
}
```
Now let's get some information from the pet object, such as the age.
```java
public class PetTester {
public static void main(String[] args) {
Pet mypet;
myPet = new Pet();
myPet.setName("Fred");
myPet.setYears(20);
int year = myPet.getYears();
}
}
```
### Constructors
Constructors lets us initialize variables in the class without having to use mutator methods.
```java
public class Pet {
private String name;
private int years;
// Default Constructor
public Pet() {
name = "";
years = 0;
}
// Non-Default Constructor
public Pet(int y, String n) {
name = n;
years = y;
}
// Mutator Methods
public void setName(String n) {
name = n;
}
public void setYears(int y) {
if (y >= 0) {
years = y;
} else {
System.out.println("No one is less than 0 years old.")
}
}
// Accessor Methods
public String getName() {
return name;
}
public int getYears() {
return years;
}
}
```
Now let us see this in action.
```java
public class PetTester {
public static void main(String[] args) {
Pet yourPet = new Pet(10, "Fluffy");
}
}
```
You can have as many constructors as you want, but they must be different.
Example:
```java
public class Pet {
...
pet() {
name = "";
years = 0;
}
pet(int y, String n) {
name = n;
years = y;
}
pet(String n) {
years = 1;
name = n;
}
...
}
```

0
content/ta/spring2018.md Normal file
View file

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]);
```

0
content/ta/summer2017.md Normal file
View file

View file

@ -0,0 +1,13 @@
# CPSC 110 Introduction to Computer Science Summer 2017
For the summer session, I didn't write in depth lecture notes. Instead I wrote short complementary blog posts help out with the labs.
[Viewing Java Applets](/blog/2017-05-24-viewing-java-applets/)
[Using System Themes in Java Swing](/blog/2017-06-05-using-system-themes-java-swing/)
[Java Swing Components](/blog/2017-06-05-java-swing-components/)
[Escape Sequences in Java](/blog/2017-08-28-escape-sequences-java/)
[Obtaining Command Line Input in Java](/blog/2017-08-28-obtaining-command-line-input-java/)