Lesson 1 - Introduction to Java
Raider Robotix and Java
FRC Team 25, Raider Robotix, uses the Java programming language for programming both the robot and the scouting system. Java is also taught in NBTHS's computer science courses.
These lessons will provide you with the building blocks of Java that are necessary to program, maintain, and understand the scouting system. It currently has two components:
- Android scouting app - collects data from scouts during events and exports it in JSON (JavaScript Object Notation) files
- Every year, this needs to be updated with the correct metrics, events, game manual, and other options, as necessary
- Desktop scouting client - compiles the JSON files from the app and outputs spreadsheets of each scouting entry and aggregated statistics for each team
- Every year, this needs to be updated with the correct metrics, which includes averages, percentages, probabilities, and standard deviations, in addition to those in the scouting app
Starting from the 2017 season, Tableau is used to visualize and analyze the data from the spreadsheets generated by the client.
The goal is to have you understand how the scouting system works and be comfortable with changing its code by next season's kickoff. If you want to work on robot programming instead, additional knowledge of WPILib API will be needed.
Lesson Structure
Generally, several concepts will be explained and grouped together to form a lesson. As each concept is taught, several practice exercises are given for you to check your understanding. There are solutions provided with the exercises, but please don't check them until you've fully attempted each exercise.
At the end of the lesson, one or two problems will be assigned on HackerRank that test your understanding of all concepts in the lesson. The site allows you to check your program against several test cases and will "grade" it (pass or fail) instantly.
Java Code Structure
Java source files have a .java
extension and each contain a class, which acts like an object (we'll get to this later). Each class/source file is located in a package, which acts as a folder to organize various files. Inside an executable program is a main method, in which the code inside it executes. In a desktop Java program, the method signature public static void main(String[] args)
is used, followed by a set of curly braces. Below is an example inside a file called Example.java
:
//Place import statements here public class Example { public static void main(String[] args) { //Write your code to execute here } }
//
). Anything following the two slashes will be ignored by the compiler when your program executes. Block comments may also be written like this:
/* Hi! * I'm a block comment. */
Note the two slashes showing the beginning/end of the comment and the asterisk on each line.
Variables
Any data or value you use in Java is stored in a variable. A variable can have one of many different datatypes. The following are common datatypes:
int
: an integer with a value between -2^{31} - 1 and 2^{31} -1 (123
,25
,-900
,0
, etc.)double
: a positive or negative decimal number (1.23
,-2.5
,1.0005
, etc.)boolean
: has either atrue
orfalse
valueString
: a sequence of characters, enclosed in a set of quotation marks ("Hello World"
,"1+1=2"
,"Raider Robotix"
, etc.)
You can declare variables with its datatype, followed by a space and its identifier, then a semicolon. The identifier must start with a letter or underscore, then be followed by more letters, underscores, or numbers, with no spaces. Valid identifiers include:
_t
motor1
MOTOR_SPEED
Generally, variables are named in a camelCase notation, where the first word is lowercase, then the remaining words are uppercase. Examples of variable declarations with camelCase naming include:
int teleOpGearsCollected; double avgKpaPerGame; boolean baselineCrossed; //multiple variables can be declared with a comma separating them String robotComment, pilotComment;
On the other hand, variables that are constant throughout a program should be named with only uppercase letters and underscores. Examples of these variables include:
double TURN_ANGLE_TOLERANCE; int LEFT_JOYSTICK_PORT; String RULES_FILEPATH; int VERSION_NUMBER;
Keep in mind that variables should not have generic identifiers like x
or var1
, but ones that are descriptive.
A variable can be assigned a value with its identifier followed by the assignment operator, =
, and its value. This value can be literal or that of another variable. A variable may be assigned a value and declared at the same time as well. Some examples:
int teleOpGearsCollected; // declaration double avgHighGoalsTeleOp = 12.555; // variable declared and value of 12.555 assigned teleOpGearsCollected = 4; // assignment afterwards boolean baselineCrossed = true, readyTakeoff = false; // two variables declared and assigned value String robotComment = "This is a good robot"; double avgTeleOpKpa = avgHighGoalsTeleOp/3; //value dependent on another variable
Output
Output to the console in Java can be executed with the following statement:
System.out.println(<some value>);
This calls the println
method on a value, where <some value>
can be a literal value or a variable. Remember to terminate the print statement with a semicolon. For example, executing
System.out.println(teleOpGearsCollected); System.out.println("gears collected in tele-op in match"); System.out.println(25);
will result in the following output:
4 gears collected in tele-op in match 25
If you don't want a new line after the output, the System.out.print(<some value>)
method may be used. Executing
System.out.print(teleOpGearsCollected); System.out.println(" gears collected in tele-op."); System.out.println("Robots are cool");
will result in the following output:
4 gears collected in tele-op. Robots are cool
An IDE
An IDE (Integrated Development Environment) will be used to program in Java. It allows you to write code, execute, and debug it in one application. I recommend using Eclipse, as NBTHS and the WPILib API uses it, though alternatives like InteliJ and BlueJ exist. We will be using Android Studio as our IDE for Android development.
To get started with Eclipse:
- Download and extract the ZIP file from the link above
- Run the executable and choose your workspace (default should work)
- Go to File > New > Java Project and name your project
- Close the Welcome window
- Right click your project and go to New > Class, and name your class (without the
.java
extension) - Write your main method (see above)
- Try replacing the comment with a statement to print
Hello World
- Press the green "Play" button to execute your program
If there are any syntax errors in your program, Eclipse will underline them in red, and the program will not run. Try fixing them by reading the error message and reviewing your code or by using Google.
A Brief Exercise
Assign the values of true
, "Raider Robotix"
, and 25
to variables. Use print statements with the variables and literal values to generate the output
Hello World! It is true that I am on Team 25, Raider Robotix 25 is the Team Number.
Click here for solution
public class PrintingExercise { public static void main(String[] args) { boolean onTeam = true; String teamNickname = "Raider Robotix"; int teamNum = 25; System.out.println("Hello World!"); System.out.print("It is "); System.out.print(onTeam); System.out.print(" that I am on Team "); System.out.print(teamNum); System.out.print(", "); System.out.println(teamNickname); System.out.print(teamNum); System.out.println(" is the Team Number"); } }
Input
To take user input, you will need to use a Scanner
object. First, you will need to import the class by placing the following import statement before the class starts (see example above):
import java.util.Scanner;
The Scanner object can be declared and constructed like this to read from the system console:
Scanner myScanner = new Scanner(System.in);
The datatype is Scanner
, and myScanner
can be any valid identifier. Note the use of the new
keyword to create a new object and the parentheses following.
Several methods can be accessed through the Scanner
object for different datatypes. A method essentially acts like a function and returns a value to the main program. These may be used to let users assign values to variables:
int anInteger = myScanner.nextInt(); String aLine = myScanner.nextLine(); // takes the next whole line
Essentially, the dot operator (.
) shows that the methods nextInt()
and nextLine()
are written in the Scanner
class, and you are accessing them from an outside class. More methods for input can be found by reading the documentation for the class. If the wrong datatype is used, there will be an error in your program.
By default, spaces and line breaks separating tokens in the input will result two different variables. For example, if the input is
Raider Robotix
executing
String teamName = myScanner.next(); System.out.println(teamName);
will output
Raider
while executing
String teamName = myScanner.nextLine(); System.out.println(teamName);
Raider Robotix
because a whitespace separates Raider
and Robotix
in the input.
Exercise
Write a program that allows prompts a user to input a string, an integer, and a floating point number, then print all three once they are inputted.
Click here for a solution
import java.util.Scanner; public class VariableInput{ public system void public static void main(String[] args) { int anInt; String aString; double aDouble; Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); anInt = scanner.nextInt(); System.out.print("Enter a string: "); aString = scanner.nextLine(); System.out.print("Enter a floating point number: "); aDouble = scanner.nextDouble(); System.out.println(anInt); System.out.println(aString); System.out.println(aDouble); } }
Operators
Operators in Java allow you to interact between different datatypes.
For these examples, we will declare
int a = 5, b = 4; double c = 2.5; String s = "Hello";
Mathematical
Evaluating these operators will result in a number of type int
if both are integers, or of type double
if at least one is a double
:
+
: adds the number (anint
ordouble
) to the left and right of ita+b
is equal to9
,a+c
is equal to7.5
-
: subtracts the number on the right from the leftb-a
is equal to-1
,b-c
is equal to1.5
*
: multiplies the number to the left and right of ita*b
is equal to20
,b*c
is equal to10.0
/
: divides the number on the left by the number on the right. However, if both numbers areint
s, integer division will occur. That is, the remainder is discarded, and only the quotient remains.a/c
is equal to2.0
,b/c
is equal to1.6
a/b
is equal to1
,b/a
is equal to0
- A literal
int
value (1
) may be converted into adouble
value by adding a decimal point and a zero (1.0
)
%
: the modulus operator,a % b
returns the remainder ofa / b
a % b
is equal to1
,b % a
is equal to4
,a % c
is equal to0.0
Exercises:
- Write a program that allows the user to input (integer) dimensions of a rectangular prism and outputs its surface area and volume
- Write a program that prints the day of the week of a day, given the day of the week of the first day of the month (where 1=Monday, 7=Sunday)
- Write a program that calculates the score of a match in FIRST Steamworks, where the user inputs the number of rotors activated during tele-op/autonomous, high/low goals in tele-op/autonomous, the times the baseline was crossed, the times robots took off, and foul points that were incurred by the opposing alliance
Rectangular prism solution
import java.util.Scanner; public class RectangularPrismExercise { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int length, height, width; System.out.print("Enter height: "); height = sc.nextInt(); System.out.print("Enter length: "); length = sc.nextInt(); System.out.print("Enter width: "); width = sc.nextInt(); System.out.println("Surface area: "); System.out.println(2*(width*height+width*length+length*height)); System.out.println("Volume: " + (height*width*length)); } }
Day of the Week Solution
import java.util.Scanner; public class DayWeekExercise { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int desiredDay, firstDay; System.out.print("Day of the week of the first day of the month (1=Monday, 7=Sunday): "); firstDay = sc.nextInt(); System.out.print("Day you want the day of the week for: "); desiredDay = sc.nextInt(); System.out.print("The day of the week of Day "); System.out.print(desiredDay); System.out.print(" of the month is "); System.out.print((desiredDay+firstDay-2)%7+1); } }
Steamworks Score Solution
import java.util.Scanner; public class SteamworksExercise { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int autoRotors, teleRotors, autoHigh, autoLow, teleHigh, teleLow, baselineCrossCount, takeoffCount, foulPoints; int AUTO_ROTOR = 60, TELE_ROTOR = 40, BASELINE = 5, TAKEOFF=40; System.out.print("Autonomous rotors: "); autoRotors = sc.nextInt(); System.out.print("Tele-op rotors: "); teleRotors = sc.nextInt(); System.out.print("Autonomous high goals: "); autoHigh = sc.nextInt(); System.out.print("Autonomous low goals: "); autoLow = sc.nextInt(); System.out.print("Tele-op high goals: "); teleHigh = sc.nextInt(); System.out.print("Tele-op low goals: "); teleLow = sc.nextInt(); System.out.print("Baseline cross count: "); baselineCrossCount = sc.nextInt(); System.out.print("Takeoff count: "); takeoffCount = sc.nextInt(); System.out.print("Foul points: "); foulPoints = sc.nextInt(); int score = AUTO_ROTOR*autoRotors+teleRotors*TELE_ROTOR +BASELINE*baselineCrossCount+TAKEOFF*takeoffCount+foulPoints +autoHigh+autoLow/3+teleHigh/3+teleLow/9; System.out.print("Score: " + score); } }
Relational
Evaluating these operators will result in a boolean value (true
or false
):
<
: less than,<=
- less than or equal tob<a
istrue
,4.5 < 0
isfalse
-2 <= c
istrue
,5<=5
istrue
>
: greater than,>=
- greater than or equal to==
: checks for equality. This can only be used for primitive datatypes, and not objectsa==5
istrue
,2.0==a/c
istrue
false == true
isfalse
- For strings, the method
someString.equals(/*another string*/)
is used for equality because a string is an object. We'll get into this more in the next lesson. s.equals("Hello")
istrue
,s.equals("World")
isfalse
!=
: checks if the two objects are not equala!=5
isfalse
,1!=a/c
istrue
false != true
istrue
Exercise
Write a program to determine if it is true that a quadratic equation of the form 0=ax^2+bx+c has a real solution, where the user inputs a, b, and c.
(Hint: For now the best way to square an integer x
is x*x
, as x^2
will not evaluate correctly)
Click for a solution
import java.util.Scanner; public class QuadraticSolutionExistsExercise { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int a,b,c; System.out.print("Enter a: "); a = sc.nextInt(); System.out.print("Enter b: "); b = sc.nextInt(); System.out.print("Enter c: "); c = sc.nextInt(); boolean hasSolution = b*b-4*a*c>=0 System.out.print("It is " + hasSolution + "that the equation 0="); System.out.print(a + "*x^2 + " + b + "*x + " + c + " has a solution"); } }
Logical
These operate on boolean values and evaluating them will also result in a boolean value:
OR Operator
Written as a || b
and evaluates to true
only if either a
or b
are true
a | b | a || b |
---|---|---|
false | false | false |
false | true | true |
true | false | true |
true | true | true |
AND Operator
Written as a && b
and evaluates to true
only if both a
and b
are true
a | b | a && b |
---|---|---|
false | false | false |
false | true | false |
true | false | false |
true | true | true |
NOT Operator
Written as !a
and evaluates to true
only if a
is false
a | !a |
---|---|
false | true |
true | false |
Exercises
Evaluate the following expressions (without actually writing any code) for when boolean a = true, b = false
and for when boolean a = true, b = true
:
(a || b) && (!a || !b)
!(a && !b) || (!a && b)
!(a && b)
Click for the answers
Expression/Condition | a = true, b = false | a = true, b = true |
---|---|---|
(a || b) && (!a || !b) | true | false |
!(a && !b) || (!a && b) | false | true |
!(a && b) | true | false |
Some Shortcuts
You already learned about the assignment operator. Here are some shortcuts used for assignment with operators, if x
and y
are numbers and both are already declared and assigned values:
x += y; // same as x = x+y x -= y; // same as x = x-y x /= y; // same as x = x/y x %= y; // same as x = x % y x++; // same as x+=1 x--; // same as x-=1
Exercise: What is the value of x
after the following is executed?
int x = 60, y = 10; y /= 5; x %= x -y; x++; x *= 4;
Click for the answer
int x = 60, y = 10; y /= 5; // x = 60, y = 2 x %= x -y; // x = 2, y = 2 x++; // x = 3, y = 2 x *= 4; // x = 12, y = 2
x
is 12.Boolean Expressions
A boolean expression is any expression that evaluates to true
or false
. It may contain literals, variables, and any of the above operators. The order of operations for evaluation are:
- Parentheses
- NOT
- Multiplication, division, modulus
- Addition, subtraction
- Greater/less than (or equal to)
- Equivalence/not equivalent
- AND
- OR
The following are valid boolean expressions if x
and y
are numbers and b
is a boolean
:
x >= 5 + y && !(y + 5 == 7 || y < 0 || !b)
takeoffPercentage / avgTakeoffPercentage + 0.1 >= 1.2 && (avgKpa >= 30 || avgGears >= 4) && teamNum !=25 && !droppedGearOften
Exercises
- The XOR (exclusive-or) operator evaluates to be true if either A or B are true, but not both. Write an expression that is logically equivalent to "A XOR B" using the AND, OR, and NOT operators
- Write a boolean expression to determine if at least 3 ranking points were earned by the red alliance in a match of FIRST Steamworks, given the scores of both the red and blue alliances, the number of gears delivered by the red alliance, whether or not the reserve gear was used, and the number of high/low goals into the red boiler in autonomous/tele-op. Use appropriate identifiers for variables and declare multiple, intermediate boolean expressions as necessary.
XOR Solution
Below is a table of the XOR operator:
a | b | a XOR b |
---|---|---|
false | false | false |
false | true | true |
true | false | true |
true | true | false |
Using this, we can write
boolean XOR = (!a && b) || (a && !b);
Steamworks ranking point solution
The following variables are given:
int redAllianceScore, blueAllianceScore; int redGears; int redHighGoalsAuto, redLowGoalsAuto; int redHighGoalsTele, redLowGoalsTele; boolean reserveGearUsed;
boolean threePlusRP = (win && (kpaReached || fourRotors)) || (tie && kpaReached && fourRotors);
boolean win = redAllianceScore > blueAllianceScore; boolean tie = redAllianceScore == blueAllianceScore; boolean fourRotors = (redGears >= 12 && reserveGearUsed) || redGears >= 13; boolean kpaReached = (redHighGoalsAuto+(redHighGoalsTele+redLowGoalsAuto)/3.0+redLowGoalsTele/9.0)>=40;
Conditionals
A conditional statement is one that executes if a particular boolean expression is true.
The if
, else
, and else-if
statements are written and used as follows:
boolean a = <some expression>; if (a) { //Code here executes if expression a is true } else if (<some boolean expression b>) { // Code here executes if expression b is true and a is false } else{ // Code here executes if a and b are both false }
if
statement may be written without any else
statements, but else
and else-if
statements must follow an if
statement or an else
statement. The boolean expression may also be placed inside the parentheses, rather than assigning its value to a boolean
variable.
These conditional statements may also be nested inside each other as follows:
boolean a = <some expression>; boolean b = <some expression>; boolean c = <some expression>; if (a) { if (c) { // Code here executes if a and c are true } else{ //Code here executes if a is true and c is false } // Code here executes as long as a is true, no matter what the value of c is } else if (b) { // Code here executes if expression b is true and a is false, no matter what the value of c is if (!c) { //Code here executes if a is false, b is true, and c is false } } else{ // Code here executes if a and b are both false }
Exercises
- Write a program to determine if a number is even or odd
- Write a program that prints the month, given its numerical value (1 to 12)
- Write a program that converts a day of the week to a number (Monday = 1, Sunday = 7)
- Write a program that converts feet to yards and vice-versa, depending on what the user wants
Odd or Even Solution
import java.util.Scanner; public class OddEven { public static void public static void main(String[] args) { System.out.print("Enter a number: "); Scanner sc = new Scanner(System.in); int num; num = sc.nextInt(); boolean isEven = num % 2 == 0 System.out.print(num + " is "); if (isEven) { System.out.println("even."); } else System.out.println("odd."); } }
Number Month Converter Solution
import java.util.Scanner; public class NumberMonthxConverter { public static void public static void main(String[] args) { System.out.print("Enter a month: "); Scanner sc = new Scanner(System.in); String day; day = sc.next(); int num; if (day.equals("Monday")) num = 1; else if (day.equals("Tuesday")) num = 2; else if (day.equals("Wednesday")) num = 3; else if (day.equals("Thursday")) num = 4; else if (day.equals("Friday")) num = 5; else if (day.equals("Saturday")) num = 6; else if (day.equals("Sunday")) num = 7; System.out.print(num); } }
Day Number Converter Solution
import java.util.Scanner; public class DayNumberConverter { public static void public static void main(String[] args) { System.out.print("Enter a month: "); Scanner sc = new Scanner(System.in); String day; day = sc.next(); int num; if (day.equals("Monday")) num = 1; else if (day.equals("Tuesday")) num = 2; else if (day.equals("Wednesday")) num = 3; else if (day.equals("Thursday")) num = 4; else if (day.equals("Friday")) num = 5; else if (day.equals("Saturday")) num = 6; else if (day.equals("Sunday")) num = 7; System.out.print(num); } }
Feet-Yard Converter Solution
import java.util.Scanner; public class FeetYardConverter { public static void public static void main(String[] args) { System.out.println("1) Feet to Yards"); System.out.println("2) Yards to Feet"); System.out.println("Enter your choice (1 or 2): "); Scanner sc = new Scanner(System.in); int choice; choice = sc.nextInt(); if (choice==1) { System.out.print("Enter the number of feet: "); int feet = sc.nextInt(); System.out.println(feet + " feet is " + (feet/3.0) + " yards"); } else{ System.out.print("Enter the number of feet: "); int yards = sc.nextInt(); System.out.println(yards + " yards is " + (yards*3) + " feet"); } } }
Assignment
Download Eclipse and complete the exercises above as necessary to check your understanding. Afterwards, sign up for a HackerRank account and complete the "A School Day" program here.
Click here to read the problem statement on this site.
I suggest that you write and test the program on Eclipse, then check if it works on HackerRank.