This week, we're diving deeper into Java. We'll learn how to make decisions in our code with conditional statements, how to repeat code with loops, and how to store collections of data with arrays.
Understand and use if, else if, and else statements.
Understand and use for and while loops.
Understand and use arrays.
Understand and use methods.
See: W3Schools Java Conditions
if, else if, else: These statements allow you to run different blocks of code based on whether a condition is true or false.
int myVar = 10;
if (myVar > 5) {
System.out.println("myVar is greater than 5");
} else if (myVar < 5) {
System.out.println("myVar is less than 5");
} else {
System.out.println("myVar is equal to 5");
}
Exercise: Write a program that checks if a number is positive, negative, or zero.
See: W3Schools Java While Loop and W3Schools Java For Loop
for loop: Use a for loop when you want to run a block of code a specific number of times.
for (int i = 0; i < 5; i++) {
System.out.println("The current value of i is: " + i);
}
while loop: Use a while loop when you want to run a block of code as long as a condition is true.
int i = 0;
while (i < 5) {
System.out.println("The current value of i is: " + i);
i++;
}
Exercise: Write a program that prints the numbers from 1 to 100. Then, write a program that prints all the even numbers from 1 to 100.
Arrays: Arrays are used to store multiple values in a single variable.
// Declare and initialize an array of integers
int[] myNumbers = {10, 20, 30, 40, 50};
// Access an element in the array
System.out.println(myNumbers[0]); // Outputs 10
// Change an element in the array
myNumbers[1] = 25;
// Loop through an array
for (int i = 0; i < myNumbers.length; i++) {
System.out.println(myNumbers[i]);
}
Exercise: Write a program that creates an array of your favorite foods and then prints each one to the console.
Functions: Functions are used to group code together and reuse it.
public class Example {
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(sum(2, 3)); // Outputs 5
}
}
Next week, we'll get into Object-Oriented Programming (OOP) in Java, which is a fundamental concept for writing FRC robot code.