Skip to main content

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

  1. The datatype used for whole numbers without any decimal places is __________.
  2. When dividing two integers, Java performs __________ division, where any remainder is discarded.
  3. A standard integer in Java is a/an __________-bit signed value.
Show answers
  1. int
  2. integer (truncating) division
  3. 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.

Unit 3 simulator
Tracks `String`, `double`, `boolean`, and `int` variables as you edit.
Supports telemetry, `gamepad1`, simple `if` blocks, and basic `setPower()` math.
Does not simulate full hardware behavior or complex Java control flow.
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.