Team Methods and Control Structures Lesson
Week 4 Team FRQ
A single if
statement only takes one condition, but what if we wanted to specify more conditions? We can add else if
and else
statements to accomplish this.
Structure:
if(condition) {
// code to execute when condition is met
} else if (condition 2) {
// code to execute when condition is false but condition 2 is true
} else {
// code to execute when condition and condition 2 are false
}
switch
statements check the value of a condition and run code blocks for different scenarios.
Structure:
switch(condition) {
case value1:
// code
break;
case value2:
// code
break;
default;
// code that should run for unspecified case
break;
}
switch
statements are especially useful for creating menus.
Method: A piece of code that runs only when it's called. It can perform specific actions on an object.
// example
myPainter.turnRight();
In this example, the method turnRight
is called on the object myPainter
. It will perform a set of actions that will allow the painter to turn right. This makes our code more readable and reusable.
public class Person {
// defining the method sleep, which can be called on future instances of Person
public static void sleep () {
// will print out zzzzzzzz when sleep is called on Person
System.out.println("zzzzzzzz");
}
public static void main(String[] args) {
Person myPerson = new Person();
myPerson.sleep();
}
}
Person.main(null);
Make a class with the following
- Complete the
Person
class with the following methods- A
weather
method telling the person to put on a jacket if it's raining outside - Modify the
sleep
method to made the person sleep at certain hours
- A