Popcorn Hack 1
// Popcorn Hack #1: Complete this code
import java.util.ArrayList;
public class PopcornHack1 {
public static void main(String[] args) {
// TODO: Use Math.pow() to calculate 3^4
Math.pow(3,4);
// TODO: Use Math.sqrt() to find square root of 64
Math.sqrt(64);
// TODO: Create ArrayList of Strings
ArrayList<String> colors = new ArrayList<String>();
// TODO: Add 3 colors ("red", "blue", "green")
colors.add("red");
colors.add("blue");
colors.add("green");
// TODO: Print the size
System.out.println(colors.size());
}
}
PopcornHack1.main(null)
Popcorn Hack 2
// Popcorn Hack #2: Complete the Book class
public class Book {
// TODO: Add 3 attributes (title, author, pages)
String title;
String author;
int pages;
// TODO: Add constructor
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
// TODO: Add displayInfo() method
public void displayInfo() {
System.out.printf("The book is %s and it was written by %s. The book is %d pages long.", title, author, pages);
}
}
// TODO: Create a Book object and test all methods
Book myBook = new Book("The Return of the King", "J. R. R.", 416);
myBook.displayInfo();
The book is The Return of the King and it was written by J. R. R.. The book is 416 pages long.
Homework Hack: Phone Class
import java.util.ArrayList;
public class Phone {
String brand;
String model;
int batteryLevel = 100;
ArrayList<String> contacts = new ArrayList<String>();
public Phone(String brand, String model) {
this.brand = brand;
this.model = model;
this.batteryLevel = 100;
this.contacts = contacts;
}
public void displayInfo() {
System.out.printf("The brand of the phone is %s. The model of the phone is %s. The battery of the phone is %d\n", brand, model, batteryLevel);
}
public void addContact(String name) {
contacts.add(name);
}
public void showContacts() {
System.out.println("Contacts: " + contacts);
}
public void usePhone (int minutes) {
batteryLevel -= minutes;
}
}
public class PhoneTest {
public static void main(String[] args) {
// Set up Samsung Phone
Phone samsungPhone = new Phone("Samsung", "25");
samsungPhone.addContact("Bob");
samsungPhone.addContact("Billy");
samsungPhone.addContact("Boe");
samsungPhone.usePhone(20);
// Set up Apple Phone
Phone applePhone = new Phone("iPhone", "17");
applePhone.addContact("Jill");
applePhone.addContact("Jane");
applePhone.addContact("Jocelyn");
applePhone.usePhone(50);
// Display info of created phones
samsungPhone.displayInfo();
samsungPhone.showContacts();
applePhone.displayInfo();
applePhone.showContacts();
}
}
PhoneTest.main(null);
The brand of the phone is Samsung. The model of the phone is 25. The battery of the phone is 80
Contacts: [Bob, Billy, Boe]
The brand of the phone is iPhone. The model of the phone is 17. The battery of the phone is 50
Contacts: [Jill, Jane, Jocelyn]