Lesson 3.4: Using int Values to Count Cycles and Repetitions
Technical Context
Counting discrete events — such as the number of game elements scored or the number of times an intake has cycled — requires whole numbers. Using the int datatype prevents logic failures where a robot might try to score "2.5 times," which is physically impossible and would crash the program's logic flow.
When int Is the Right Tool
An int (integer) is a 32-bit primitive used for whole numbers ranging from approximately −2 billion to +2 billion. In robotics, int is essential for indexing through arrays of motors or counting the specific number of encoder ticks reported by a DcMotor. Unlike double, an int does not store decimal information; if you divide 5 by 2 using integers, Java will return 2, completely discarding the remainder.
Annotated Code
@TeleOp(name="Cycle_Counter")
public class CycleCounter extends OpMode {
// Declaring an int to store the total count of scored items
int pixelCount = 0;
boolean wasPressed = false;
@Override
public void init() {
telemetry.addData("System", "Counter Reset to Zero");
}
@Override
public void loop() {
// Incrementing the integer count on each new button press
if (gamepad1.a && !wasPressed) {
pixelCount++; // Shorthand for pixelCount = pixelCount + 1
}
wasPressed = gamepad1.a;
telemetry.addData("Pixels Scored", pixelCount);
}
}
Fill-in-the-Blank Practice
- The datatype used for whole numbers without any decimal places is
__________. - When dividing two integers, Java performs
__________division, where any remainder is discarded. - A standard integer in Java is a/an
__________-bit signed value.
Show answers
int- integer (truncating) division
- 32
Template Challenge
Robot Scenario: Your autonomous requires the robot to keep track of how many "laps" it has completed. Declare an int variable and increment it every time the "B" button is pressed.
Show answer
int laps = 0;
@Override
public void init() {
laps = 0;
}
@Override
public void loop() {
if (gamepad1.b) {
laps++;
}
telemetry.addData("Laps completed", laps);
}
Ready to move on?
Sign in with Google to save your progress with Telemark, or continue without saving.