CS62 - Spring 2021 - Lab 2
Example code in this lecture
CardDealer
Lecture notes
What does the constructor do in CardDealer in
CardDealer code
- What does the constructor do?
- creates a new array for number of decks * 13 * 4 entries
- adds each card for each deck to the array
- outer loop is over the number of decks
- second loop is over suits
- third loop is over numbers
initializing arrays
- often, we'll initialize an array and then fill it in, e.g.,
int[] x = new int[10];
x[0] = 2;
...
- sometimes (e.g., with constants), we'll want to initialize the array with values. To do this, use curly braces
int[] x = {1, 2, 3, 4, 5};
Look at the CardDealer in
CardDealer code
- What does the shuffle method do?
- for each card, pick another random entry and swap the entries
- Where does Random come from?
- it's another class that we imported!
A package is a collection of classes
- usually they're related
- Any class inside a particular package may use any other class in the package without doing anything special
- If you want to use a class that is not inside your package, you need to import it
- To import a class:
import <package_name>.<class_name>
- sometimes, there are nested packages, e.g.
import <outer_package>.<inner_package>.<class_name>
- For example:
import java.util.Random
- imports the Random class from the java.util package
import java.util.Scanner
- imports the Scanner class from the java.util package
- To write your own package:
- Packages are indicated in two ways (both are required):
1) All classes inside a packages should be in a directory with the packages name
2) All classes inside a package should start with package <package_name>;
Look at the CardDealer in
CardDealer code
- What does the printDeck method do?
- it's static, so it doesn't have access to the instance variables
- creates a new card dealer and then prints out the entire deck
- utilizes next and getNext
- both use position to keep track of where we are
- using this pair of methods is a common way to iterate through data. we'll see it a lot!
Look at the CardPrinter class in
CardDealer code