Title: Java Basics
Author: John Doe
Pages: 350
Is the book long? true
// Homework Hack: Complete the Phone class
import java.util.ArrayList;
public class Phone {
ArrayList<String> contacts;
String model;
String battery;
int batteryLevel;
public Phone(String model, String battery, int batteryLevel) {
this.contacts = new ArrayList<>();
this.model = model;
this.battery = battery;
this.batteryLevel = batteryLevel;
}
public Phone(String model, String battery) {
this.contacts = new ArrayList<>();
this.model = model;
this.battery = battery;
this.batteryLevel = 100; // Default battery level is 100%
}
void displayInfo() {
System.out.println("Model: " + model);
System.out.println("Battery: " + battery);
System.out.println("Battery Level: " + batteryLevel + "%");
}
void addContact(String name) {
contacts.add(name);
System.out.println(name + " added to contacts.");
}
void showContacts() {
System.out.println("Contacts: " + contacts);
}
void usePhone(int minutes) {
int batteryUsage = minutes / 2; // Assume 1% battery used every 2 minutes
batteryLevel -= batteryUsage;
if (batteryLevel < 0) batteryLevel = 0;
System.out.println("Used phone for " + minutes + " minutes. Battery level is now " + batteryLevel + "%.");
}
}
// Test your Phone class
public class PhoneTest {
public static void main(String[] args) {
// Create 2 Phone objects
Phone phone1 = new Phone("Model X", "Lithium-Ion", 80);
Phone phone2 = new Phone("Model Y", "Nickel-Cadmium");
// Add 3 contacts to each
phone1.addContact("Alice");
phone1.addContact("Bob");
phone1.addContact("Charlie");
phone2.addContact("David");
phone2.addContact("Eve");
phone2.addContact("Frank");
// Use phones for some minutes
phone1.usePhone(30);
phone2.usePhone(50);
// Display all information
phone1.displayInfo();
phone1.showContacts();
phone2.displayInfo();
phone2.showContacts();
}
}
PhoneTest.main(null);
Alice added to contacts.
Bob added to contacts.
Charlie added to contacts.
David added to contacts.
Eve added to contacts.
Frank added to contacts.
Used phone for 30 minutes. Battery level is now 65%.
Used phone for 50 minutes. Battery level is now 75%.
Model: Model X
Battery: Lithium-Ion
Battery Level: 65%
Contacts: [Alice, Bob, Charlie]
Model: Model Y
Battery: Nickel-Cadmium
Battery Level: 75%
Contacts: [David, Eve, Frank]