![]() |
Home | Methods & Control Structures | Class Implementation | Arrays/ArrayLists | 2D Arrays |
Question 2 — Class Implementation
Notes on FRQ Question
Things to look out for
- Don’t have random code that isn’t necessary a. For example, random print statements shouldn’t be there
- Forgetting to declare variables
- Void methods and constructors shouldn’t return values
Steps to solving the problem
- Writing the class header (
public class ClassName { ... }
) - Declare the instance variables (
private int skibidi;
) a. Usually should be private - Declare constructor header (
public ClassName(...) { ... }
) a. Should usually be public - Declare method headers (
public void sampleMethod(...) { ... }
) a. Should usually be public, but it may be private if the question says so - Write the actual logic in the methods now
Example - 2020 FRQ Part 2
9/9 Points
import java.util.Random;
public class GameSpinner {
private int numSectors;
private int lastSpin;
private int runLength;
private Random rand;
public GameSpinner(int sectors) {
numSectors = sectors;
lastSpin = -1;
runLength = 0;
rand = new Random();
}
public int spin() {
int result = rand.nextInt(numSectors) + 1;
if (result == lastSpin) {
runLength++;
} else {
runLength = 1;
lastSpin = result;
}
return result;
}
public int currentRun() {
return runLength;
}
}