Website snapshot

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

View file

@ -0,0 +1,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;
}
...
}
```