Methods
So far you've learned to store data and make decisions. But what happens when you need to do the same task multiple times? Methods (also called functions) let you package up code into reusable blocks that you can call whenever you need them.
Example:`
// Define the method
public void sayHello() {
telemetry.addLine("Hello, FTC team!");
}
// Call the method
sayHello(); // Prints: Hello, FTC team!
Method Structure
Every method has the same basic parts:
accesMod returnType methodName(parameters) {
// Code that does the work
return someValue; // Only if returnType isn't void
}
accesMod- Can either be public or private. Determines whether other parts of your program can use this method or not.returnType- What type of data this method gives back (orvoidfor nothing)methodName- What you call this methodparameters- Data you pass into the method (optional)
Methods That Don't Return Anything
These methods do work but don't give you back a value. They use void as the return type:
public void disableSliders(){
left.setMotorDisable();
right.setMotorDisable();
}
Methods That Return Values
These methods calculate something and give you back the result:
public static double getY() {return y;}
tip
When a method returns a value, you usually want to store that value in a variable or use it in an expression.
Methods With Parameters
Parameters let you pass information into your methods to make them more flexible:
public void setPowerVec(Vector vector){
//Apply power
frontLeft.setPower((powerVector.getX() + powerVector.getY() + powerVector.getZ()));
frontRight.setPower((powerVector.getX() - powerVector.getY() - powerVector.getZ()));
backLeft.setPower((powerVector.getX() - powerVector.getY() + powerVector.getZ()));
backRight.setPower((powerVector.getX() + powerVector.getY() - powerVector.getZ()));
}
Multiple Parameters
Methods can take several parameters separated by commas:
public void moveToPosition(double x, double y, double power) {
//Code to move robot to certain position
}
Quick Reference
| Method Type | Example | When to Use |
|---|---|---|
| Void (no return) | public void moveForward() | Performing actions |
| Return value | public int getScore() | Calculating/getting data |
| With parameters | public void turn(double degrees) | Flexible, reusable actions |
| Multiple parameters | public void move(double x, double y) | Complex operations |