Lesson Homework
Homework Solutions for Lessons
- Unit 1 - Primitives
- Unit 2 - Using Objects
- Unit 3 - Boolean expressions
- Unit 4 - Iteration
- Unit 5 - Writing Classes
- Unit 6 - Arrays
- Unit 7 - Arraylists
- Unit 9 - Inheritance
public double purchasePrice() {
total = 0;
total = getListPrice() * (1+ taxRate);
return total;
}
public int compareCustomer(Customer other) {
int numberCompare = getName().compareTo(other.getName());
if (numberCompare == 0) {
return this.getID() - other.getID();
} else {
return numberCompare;
}
}
public class Goblin {
private String name;
private int HP;
private int DMG;
private double hitChance;
private double criticalHitChance;
public String getName() {
return name;
}
public int getHP() {
return HP;
}
public int getDMG() {
return DMG;
}
public double getHitChance() {
return hitChance;
}
public double getCriticalHitChance(){
return criticalHitChance;
}
public boolean isAlive() {
if (this.HP > 0) {
return true;
} else {
return false;
}
}
public void setName(String newName) {
this.name = newName;
}
public void setHP(int newHP) {
this.HP = newHP;
}
public void takeDMG(int takenDamage) {
this.HP -= takenDamage;
}
public void setDMG(int newDMG) {
this.DMG = newDMG;
}
public void setHitChance(double newHitChance) {
this.hitChance = newHitChance;
}
public void setCriticalHitChance(double newCriticalHitChance) {
this.criticalHitChance = newCriticalHitChance;
}
}
import java.lang.Math;
public class Duel {
public static void attack(Goblin attackerGoblin, Goblin attackeeGoblin) {
System.out.println(attackerGoblin.getName() + " attacks " + attackeeGoblin.getName() + "!");
if (Math.random() < attackerGoblin.getHitChance()) {
if (Math.random() < attackerGoblin.getCriticalHitChance()){
attackeeGoblin.takeDMG(2*attackerGoblin.getDMG());
System.out.println(attackerGoblin.getName() + " lands a critical hit!");
System.out.println(attackeeGoblin.getName() + " takes " + 2*attackerGoblin.getDMG() + " damage");
}
else{
attackeeGoblin.takeDMG(attackerGoblin.getDMG());
System.out.println(attackerGoblin.getName() + " hits!");
System.out.println(attackeeGoblin.getName() + " takes " + attackerGoblin.getDMG() + " damage");
}
} else {
System.out.println(attackerGoblin.getName() + " misses...");
}
System.out.println(attackeeGoblin.getName() + " HP: " + attackeeGoblin.getHP());
System.out.println();
}
public static void fight(Goblin goblin1, Goblin goblin2) {
while (goblin1.isAlive() && goblin2.isAlive()) {
attack(goblin1, goblin2);
if (!goblin1.isAlive()) {
System.out.println(goblin1.getName() + " has perished");
break;
}
attack(goblin2, goblin1);
if (!goblin2.isAlive()) {
System.out.println(goblin2.getName() + " has perished");
break;
}
}
}
public static void main(String[] args) {
Goblin goblin1 = new Goblin();
goblin1.setName("jeffrey");
goblin1.setHP(12);
goblin1.setDMG(2);
goblin1.setHitChance(0.50);
goblin1.setCriticalHitChance(0.1);
Goblin goblin2 = new Goblin();
goblin2.setName("Gunther the great");
goblin2.setHP(4);
goblin2.setDMG(1);
goblin2.setHitChance(1);
goblin1.setCriticalHitChance(0.5);
fight(goblin1, goblin2);
}
}
Duel.main(null);
public int getChargeStartTime(int chargeTime) {
int time = 0;
for (int i =1; i< 24; i++) {
if (this.getChargingCost(i, chargeTime) < this.getChargingCost(time, chargeTime)) {
time =i;
}
}
return time;
}
public boolean isStrictlyIncreasing() {
for (int i =1; i < digitList.size(); i++) {
if (digitList.get(i-1) < digitList.get(i)) {
return true;
} else {
return false;
}
}
}
public boolean isBalanced(ArrayList<String> delimiters) {
int numOpen =0;
int numClosed = 0
for (int i =0; i <delimiters.size(); i++) {
if (delimiters.get(i).equals(openDel)) {
numOpen++;
}
if (delimiters.get(i).equals(closeDel)) {
numOpen++;
}
}
if (numClosed == numOpen) {
return true;
} else {
return false;
}
}
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.JOptionPane;
public class Gui implements ActionListener {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton submitButton = new JButton("Submit");
JTextField fieldString = new JTextField(20);
JLabel label = new JLabel();
int numGuesses = 1;
boolean numCorrect = false;
Random rand = new Random();
int randomNumber = rand.nextInt(100);
void go() {
frame.add(panel);
panel.add(fieldString);
panel.add(submitButton);
panel.add(label);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
submitButton.addActionListener(this);
frame.setSize(new Dimension(500, 500));
label.setText("Enter a number between 1 and 100");
}
public static void main(String[] args) {
Gui gui = new Gui();
gui.go();
}
@Override
public void actionPerformed(ActionEvent e) {
int field = Integer.parseInt(fieldString.getText());
System.out.println(randomNumber);
System.out.println(field);
if (numCorrect == false) {
if (field > randomNumber) {
JOptionPane.showMessageDialog(null, "Guess too high, try again. Amount of Guesses: " + numGuesses);
numGuesses += 1;
fieldString.setText("");
} else if (field < randomNumber) {
JOptionPane.showMessageDialog(null, "Guess too low, try again. Amount of Guesses: " + numGuesses);
numGuesses += 1;
fieldString.setText("");
} else if (field == randomNumber) {
JOptionPane.showMessageDialog(null, "Correct Guess. Amount of Guesses: " + numGuesses);
numCorrect = true;
System.exit(0);
}
}
}
}
Gui.main(null);
Unit 5 - Writing Classes
- Object is the instance of a class
- Class is the overall blueprint of the thing
- Methods are functions or behaviors that the objects do
- Constructors initiailize some of the private variables and creates object
- Some variables might be private so you need getter and setter methods to access and modify the data
public int scoreGuess (String guess) {
int count = 0;
for (int i = 0; i <= secret.length() - guess.length(); i++) {
if (secret.substring(i, i + guess.length()).equals(guess)) {
count++;
}
}
return count * guess.length() * guess.length();
}
public void addMembers(String[] names, int gradYear ) {
for( String n : names ) {
memberList.add(new MemberInfo( n, gradYear, true) );
}
}
Unit 6 - Arrays
- ArrayList in java
- Use a for loop to acces an array
- bound errors or uninitialized and unfilled arrays are usual errors
- Enhanced loop to traverse array
- int[] array = new int[5]; int[] array = [10, 2, 3, 4, 5];
- CollegeBoard will usually have a for loop and skip iterations and change the value of variable
import java.util.ArrayList;
public class ArrayHW {
ArrayList<Integer> values = new ArrayList<Integer>();
public void initialize() {
for (int i = 0; i < 10; i++) {
values.add(i);
}
}
public void printEven() {
for (int i = 0; i < values.size(); i++) {
if (values.get(i) % 2 == 0) {
values.set(i, 0);
System.out.print(values.get(i));
} else {
System.out.print(values.get(i));
}
}
}
public void swap(){
int lastElement = values.get(values.size()-1);
values.set(values.size()-1, values.get(0));
values.set(0, lastElement);
for (int i = 0; i < values.size(); i++) {
System.out.print(values.get(i));
}
}
public void print() {
for (int i = 0; i < values.size(); i++) {
System.out.print(values.get(i));
}
}
public static void main(String[] args) {
ArrayHW arrayHW = new ArrayHW();
System.out.println("Initializing");
arrayHW.initialize();
arrayHW.print();
System.out.println("\nPrinting Even");
arrayHW.printEven();
System.out.println("\nSwapping Elements");
arrayHW.swap();
}
}
ArrayHW.main(null);
Unit 7 - Arraylists
- ArrayList
name = new ArrayList ();</li> - name.add(value)
- name.remove(value)
- name.size()
- Collections.sort(name)
- You can use iteration to traverse the arraylist and find values
</ul> </div> </div> </div>import java.util.ArrayList; import java.util.Collections; import java.util.Random; ArrayList<Integer> arr = new ArrayList<>(); Random rand = new Random(); for (int i =0; i< 10; i++) { int random_int = rand.nextInt(10); arr.add(i * random_int); } public void print(ArrayList<Integer> idk) { for (int i = 0; i < idk.size(); i++) { System.out.print(idk.get(i) + " "); } System.out.println(); } print(arr); // HashCode DIsply System.out.println("Hash map before operation: "+ arr.hashCode()); Collections.sort(arr); System.out.println("Hash map after operation: "+ arr.hashCode()); // Swap first and last element int temp = arr.get(0); int temp2 = arr.get(arr.size() -1); arr.set(0, temp2); arr.set(arr.size() - 1, temp); System.out.print("Swapped First and Last Element: "); print(arr); // sort in descending order Collections.sort(arr, Collections.reverseOrder()); System.out.print("Sort in Descending: "); print(arr);
public class Worldcup { //superclass int wins = 0; int losses = 0; boolean cool; public Worldcup(int wins, int losses, boolean cool){ this.wins = wins; this.losses = losses; this.cool = cool; } public String toString(){ return "Wins: " + this.wins + ", Losses: " + this.losses + ", Cool?: " + this.cool; } } public class Argentina extends Worldcup { public Argentina(int wins, int losses, boolean cool) { super(wins, losses,cool); } public static void main(String[] args) { Argentina argobj = new Argentina(3,1,true); System.out.println(argobj.toString()); } } public class Brazil extends Worldcup { public Brazil(int wins, int losses, boolean cool) { super(wins, losses,cool); } public static void main(String[] args) { Argentina argobj = new Argentina(4,2,true); System.out.println(argobj.toString()); } } Argentina.main(null); Brazil.main(null);
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } } public class Student extends Person { private String extra; public Student(String name, int age, String extra) { super(name, age); this.extra = extra; } public String getExtra() { return this.extra; } @Override public String toString(){ return "Name: " + getName() + ", Age: " + getAge() + ", Extra: " + getExtra(); } } public class Main{ public static void main(String[] args){ Student bro = new Student("bro", 16, "Basketball"); System.out.println(bro.toString()); } } Main.main(null);