Unit 3: Version Control and Troubleshooting
In programming, certain situations are naturally prone to errors. We call these "hot spots." By learning to recognize these areas, you can approach them with extra caution, anticipate potential bugs, and write more robust code from the start.
These areas tend to be tricky due to subtle syntax, logical complexity, or interactions with unpredictable external systems like user input.
Here are the most common areas where you'll encounter bugs. Pay close attention when working with these concepts.
The Trap: Calling a method on an object reference that is `null`. This is the single most common cause of robot code crashes.
Why it's a Hot Spot: It's easy to declare a variable (like a motor) but forget to initialize it in the constructor, leaving it `null`.
public class IntakeSubsystem extends SubsystemBase {
private Spark m_intakeMotor; // Hot Spot: Declared but not initialized!
public IntakeSubsystem() {
// ERROR: We forgot to write: m_intakeMotor = new Spark(5);
}
public void runIntake() {
m_intakeMotor.set(0.8); // CRASH! Throws NullPointerException because m_intakeMotor is null.
}
}
The Trap: Trying to access an array element using an index that doesn't exist. Remember, arrays are 0-indexed, so the last valid index is always `length - 1`.
Why it's a Hot Spot: "Off-by-one" errors in loops are very common.
double[] motorSpeeds = {0.2, 0.4, 0.6}; // Length is 3, valid indices are 0, 1, 2.
// Hot Spot: The '<=' causes an off-by-one error. The loop will try to access motorSpeeds[3].
for (int i = 0; i <= motorSpeeds.length; i++) {
System.out.println(motorSpeeds[i]); // CRASHES on the last iteration!
}
The Trap: A user enters data that doesn't match what your `Scanner` is expecting, causing an `InputMismatchException`.
Why it's a Hot Spot: User input is unpredictable. Your code must be prepared to handle invalid data gracefully.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter target angle (number): ");
// Hot Spot: What if the user types "ninety"?
int angle = scanner.nextInt(); // CRASH! Throws InputMismatchException.
The Trap: Using a single equals sign (`=`) to check for equality inside an `if` statement. `=` assigns a value, while `==` compares two values.
Why it's a Hot Spot: It's a subtle typo that can lead to confusing logical errors. While Java's type system catches this in many cases, it's a critical concept to master.
boolean isRedAlliance = false;
// Hot Spot: This line ASSIGNS true to isRedAlliance, and the condition becomes 'if (true)'.
// This is a compilation error in Java in this context, but in other languages it's a sneaky bug.
if (isRedAlliance = true) {
System.out.println("This will always run!");
}
// Correct way to compare
if (isRedAlliance == true) { ... }
Question: A programmer writes a `for` loop to iterate through an array named `motors` that has 5 elements. Which loop condition contains a classic "off-by-one" error that will cause a crash?