coe318/lab1/Resistor.java
/**
* A Resistor models an ideal resistor that obeys Ohm's Law.
*
* @author Rocky Wang
*/
package coe318.lab1;
public class Resistor {
//Instance (state) variables
//TODO Add instance variables (Hint: you only need 2!)
private double resistanceValue;
private double voltageValue;
/**
* Create an ideal Resistor. The initial current through and voltage across
* the Resistor are zero.
*
* @param resistance resistance in Ohms
*/
public Resistor(double resistance) {
//Set values of state variables
resistanceValue = resistance;
}
/**
* Returns the value of the resistor in Ohms.
*
* @return the resistance
*/
public double getResistance() {
//FIX THIS so that it returns the actual resistance
return resistanceValue;
}
/**
* Returns the voltage across the resistor.
*
* @return the voltage
*/
public double getVoltage() {
//FIX THIS so that it returns the actual voltage
return voltageValue;
}
/**
* Sets the value of the voltage across the resistor.
*
* @param voltage the voltage to set
*/
public void setVoltage(double voltage) {
//FIX THIS. Only set the voltage value if the parameter
//is between 50 and -50, otherwise print an error message.
if (voltage >= -50 && voltage <= 50){
voltageValue = voltage;
}else{
System.out.println("Error: voltage value beyond limit");
}
}
/**
* Returns the current through the Resistor.
*
* @return the current
*/
public double getCurrent() {
//FIX THIS
return voltageValue / resistanceValue;
}
/**
* Sets the value of the current through the resistor.
*
* @param current the current to set
*/
public void setCurrent(double current) {
//FIX THIS.Only set the current value if the parameter
//is between 5 and -5, otherwise print an error message.
if(current >= -5 && current <= 5){
voltageValue = current*resistanceValue;
}else{
System.out.println("Error: current value beyond limit");
}
}
/**
* Returns the power (in Watts) dissipated by the Resistor.
*
* @return the power
*/
public double getPower() {
//FIX THIS
return voltageValue*(voltageValue/resistanceValue);
}
/**
* A simple example of using a Resistor.
* <p>
* The output should be:
* <pre>
* Creating a 50 Ohm resistor (r1)
* Its resistance is 50.0 Ohms
* Its current is 0.0 Amps
* Its voltage is 0.0 Volts
* * Its power is 0.0 Watts
* Creating a 100 Ohm resistor (r2)
* Its resistance is 100.0 Ohms
* Setting r1's current to 10 Amps
* Error: current value beyond limit
* Setting r1's current to 2 Amps
* Its current is 2.0 Amps
* Its voltage is 100.0 Volts
* Its power is 200.0 Watts
* Setting r1's voltage to 90 Volts
* Error: voltage value beyond limit
* Setting r1's voltage to 50 Volts
* Its current is 1.0 Amps
* Setting r2's current to 3 Amps
* Its voltage is 300.0 Volts
* </pre>
*
* @param args (Command line arguments not used.)
*/
public static void main(String[] args) {
Resistor r1, r2;
System.out.println("Creating a 50 Ohm resistor (r1)");
r1 = new Resistor(50.0);
System.out.println("Its resistance is "
+ r1.getResistance() + " Ohms");
System.out.println("Its current is "
+ r1.getCurrent() + " Amps");
System.out.println("Its voltage is "
+ r1.getVoltage() + " Volts");
System.out.println("Its power is "
+ r1.getPower() + " Watts");
System.out.println("Creating a 100 Ohm resistor (r2)");
r2 = new Resistor(100.0);
System.out.println("Its resistance is "
+ r2.getResistance() + " Ohms");
System.out.println("Setting r1's current to 10 Amps");
r1.setCurrent(10.0);
System.out.println("Setting r1's current to 2 Amps");
r1.setCurrent(2.0);
System.out.println("Its current is "
+ r1.getCurrent() + " Amps");
System.out.println("Its voltage is "
+ r1.getVoltage() + " Volts");
System.out.println("Its power is "
+ r1.getPower() + " Watts");
System.out.println("Setting r1's voltage to 90 Volts");
r1.setVoltage(90.0);
System.out.println("Setting r1's voltage to 50 Volts");
r1.setVoltage(50.0);
System.out.println("Its current is "
+ r1.getCurrent() + " Amps");
System.out.println("Setting r2's current to 3 Amps");
r2.setCurrent(3.0);
System.out.println("Its voltage is "
+ r2.getVoltage() + " Volts");
}
}
coe318/lab2/ComplexNumber.java
package coe318.lab2;
/**
* ComplexNumber models a complex number expressed in rectangular form (real and
* imaginary parts). It is an <em>immutable</em> object.
*
* @author Your Name
*/
public class ComplexNumber {
//Instance variable declarations
private double real;
private double imaginary;
/**
* Construct a ComplexNumber given its real and imaginary parts.
*
* @param re The real component
* @param im The imaginary component
*/
public ComplexNumber(double re, double im) {
//Initialize the instance variables
this.real = re;
this.imaginary = im;
}
/**
* Returns the real component.
*
* @return the real
*/
public double getReal() {
return this.real; //A stub: to be fixed
}
/**
* Returns the imaginary component.
*
* @return the imaginary
*/
public double getImaginary() {
return this.imaginary; //A stub: to be fixed
}
/**
* Returns a new ComplexNumber number that is the negative of <em>this</em>.
* Note: the original ComplexNumber is <b>NOT</b>
* modified.
*
* @return -this
*/
public ComplexNumber negate() {
return new ComplexNumber(-real, -imaginary); //A stub: to be fixed
}
/**
* Returns a new ComplexNumber that is the sum of <em>this</em> and
* <em>z</em>. Note: the original ComplexNumber is
* <b>NOT</b> modified.
*
* @param z
* @return this + z
*/
public ComplexNumber add(ComplexNumber z) {
return new ComplexNumber(real + z.getReal(), imaginary + z.getImaginary()); //A stub: to be fixed
}
/**
* Returns a new ComplexNumber that is the difference of <em>this</em> and
* <em>z</em>. Note: the original ComplexNumber is
* <b>NOT</b> modified.
*
* @param z
* @return this + z
*/
public ComplexNumber subtract(ComplexNumber z) {
return new ComplexNumber(real - z.getReal(), imaginary - z.getImaginary()); //A stub: to be fixed
}
/**
* Returns a new ComplexNumber that is the product of <em>this</em> and
* <em>z</em>. Note: the original ComplexNumber is
* <b>NOT</b> modified.
*
* @param z
* @return this * z
*/
public ComplexNumber multiply(ComplexNumber z) {
double r = z.getReal(), i = z.getImaginary();
return new ComplexNumber(real * r - imaginary * i, real * i + imaginary * r); //A stub: to be fixed
}
/**
* Returns a new ComplexNumber that is the reciprocal of <em>this</em>.
* Note: the original ComplexNumber is
* <b>NOT</b> modified.
*
* @return 1.0 / this
*/
public ComplexNumber reciprocal() {
double d = real * real + imaginary * imaginary;
return new ComplexNumber(real / d, -imaginary / d); //A stub: to be fixed
}
/**
* Returns a new ComplexNumber that is
* <em>this</em> divided by <em>z</em>. Note: the original ComplexNumber is
* <b>NOT</b> modified.
*
* @param z
* @return this / z
*/
public ComplexNumber divide(ComplexNumber z) {
return this.multiply(z.reciprocal()); //A stub: to be fixed
}
/**
* Returns a String representation of
* <em>this</em> in the format:
* <pre>
* real +-(optional) i imaginary
* </pre> If the imaginary part is zero, only the real part is converted to
* a String. A "+" or "-" is placed between the real and imaginary parts
* depending on the the sign of the imagrinary part.
* <p>
* Examples:
* <pre>
* ..println(new ComplexNumber(0,0); -> "0.0"
* ..println(new ComplexNumber(1,1); -> "1.0 + i1.0"
* ..println(new ComplexNumber(1,-1); -> "1.0 - i1.0"
* </pre>
*
* @return the String representation.
*/
@Override
public String toString() {
//DO NOT MODIFY THIS CODE!
String str = "" + this.getReal();
if (this.getImaginary() == 0.0) {
return str;
}
if (this.getImaginary() > 0) {
return str + " + i" + this.getImaginary();
} else {
return str + " - i" + -this.getImaginary();
}
}
}
coe318/lab2/ComplexTry.java
package coe318.lab2;
/**
* Do <b>NOT</b> modify this class. Its output will be used as part of the
* marking procedure for this lab.
*
* @author kclowes
*/
public class ComplexTry {
/**
* The output should be:
* <pre>
* a = 1.0 + i2.0
* b (-a) = -1.0 - i2.0
* c = 2.0 + i3.0
* d (a + c) = 3.0 + i5.0
* e (a - c) = -1.0 - i1.0
* f (1 / a) = 0.2 - i0.4
* g (a / c) = 0.6153846153846154 + i0.07692307692307693
* h (a * c) = -4.0 + i7.0
* </pre>
*
* @param args Command line args not used.
*/
public static void main(String[] args) {
ComplexNumber a, b, c, d, e, f, g, h;
a = new ComplexNumber(1, 2);
System.out.println("a = " + a);
b = a.negate();
System.out.println("b (-a) = " + b);
c = new ComplexNumber(2, 3);
System.out.println("c = " + c);
d = a.add(c);
System.out.println("d (a + c) = " + d);
e = a.subtract(c);
System.out.println("e (a - c) = " + e);
f = a.reciprocal();
System.out.println("f (1 / a) = " + f);
g = a.divide(c);
System.out.println("g (a / c) = " + g);
h = a.multiply(c);
System.out.println("h (a * c) = " + h);
}
}
Counter.java
/**
*
* @author Your Name
*/
package coe318.lab3;
public class Counter {
//Instance variables here
private int m;
private Counter l;
private int d;
public Counter(int modulus, Counter left) {
m = modulus;
l = left;
}
/**
* @return the modulus
*/
public int getModulus() {
return m;
}
/**
* Returns the Counter to the left attached to this
* Counter. Returns null if there is no Counter
* to the left.
* @return the left
*/
public Counter getLeft() {
return l;
}
/**
* @return the digit
*/
public int getDigit() {
return d;
}
/**
* @param digit the digit to set
*/
public void setDigit(int digit) {
d = digit;
}
/**
* Increment this counter. If it rolls over,
* its left Counter is also incremented if it
* exists.
*/
public void increment() {
d++;
if (d==m){
d = 0;
if (l != null){
l.increment();
}
}
}
/** Return the count of this Counter combined
* with any Counter to its left.
*
* @return the count
*/
public int getCount() {
if (l == null){
return d;
}else{
return d + m * l.getCount();
}
}
/** Returns a String representation of the Counter's
* total count (including its left neighbour).
* @return the String representation
*/
@Override
public String toString() {
//DO NOT MODIFY THIS CODE
return "" + getCount();
}
}
CounterTry.java
package coe318.lab3;
/**
*
* @author kclowes
*/
public class CounterTry {
/**
* The output should be:
* <pre>
* d0 = 0
* d0 = 1
* d0 = 2
* d0 = 0
*
* Two digit counter...
* d1, d2 digits: 00 d0 count = 0
* d1, d2 digits: 01 d0 count = 1
* d1, d2 digits: 02 d0 count = 2
* d1, d2 digits: 03 d0 count = 3
* d1, d2 digits: 10 d0 count = 4
* d1, d2 digits: 11 d0 count = 5
* d1, d2 digits: 12 d0 count = 6
* d1, d2 digits: 13 d0 count = 7
* d1, d2 digits: 20 d0 count = 8
* d1, d2 digits: 21 d0 count = 9
* </pre>
* @param args the command line arguments
*/
public static void main(String[] args) {
Counter d1, d0;
d0 = new Counter(3, null);
for (int i = 0; i < 4; i++) {
System.out.println("d0 = " + d0);
d0.increment();
}
System.out.println("\nTwo digit counter...");
d1 = new Counter(4, null);
d0 = new Counter(4, d1);
for (int i = 0; i < 10; i++) {
System.out.println("d1, d2 digits: " +
d1.getDigit() + d0.getDigit() + " d0 count = " + d0);
d0.increment();
}
}
}Account.java
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author rocky
*/
package coe318.lab4;
public class Account {
private String name;
private int num;
private double bal;
public Account(String name, int number, double initialBalance){
this.name = name;
this.num = number;
this.bal = initialBalance;
}
public String getName() {
return this.name;
}
public double getBalance() {
return this.bal;
}
public int getNumber() {
return this.num;
}
public boolean deposit(double amount) {
if(amount<=0){
return false;
}else{
this.bal += amount;
return true;
}
}
public boolean withdraw(double amount) {
if(amount <=0){
return false;
}else if (amount > this.bal){
return false;
}else{
this.bal -= amount;
return true;
}
}
@Override
public String toString() {//DO NOT MODIFY
return "(" + getName() + ", " + getNumber() + ", "+ String.format("$%.2f", getBalance()) + ")";
}
}
Bank.java
/**
*
* @author rocky
*/
package coe318.lab4;
public class Bank {
private String name;
/**
* An array of Accounts managed by this bank.
*/
private Account[] accounts;
private int numAccounts;//number of active accounts
public Bank(String name, int maxNumberAccounts) {
this.name = name;
accounts = new Account[maxNumberAccounts];
numAccounts = 0;
}
/**
* @return the name
*/
public String getName() {
return this.name; //Fix this
}
/**
* @return the numAccounts
*/
public int getNumAccounts() {
return this.numAccounts; //Fix this
}
public Account[] getAccounts() {
return this.accounts; //Fix this
}
/**
* Return true if the Bank already has an account with this number;
* otherwise false.
*
* @param accountNumber
* @return
*/
public boolean hasAccountNumber(int accountNumber) {
for (int i = 0; i < numAccounts; i++) {
if (accounts[i].getNumber() == accountNumber) {
return true;
}
}
return false;
}
/**
* Adds the specified account to the Bank if possible. If the account number
* already exists or the Bank has reached its maximum number of accounts,
* return false and do not add it; otherwise, add it and return true.
*
* @param account
* @return true if successful
*/
public boolean add(Account account) {
if (hasAccountNumber(account.getNumber()) || numAccounts >= accounts.length) {
return false;
}
accounts[numAccounts] = account;
numAccounts++;
return true;
}
@Override
public String toString() {
//DO NOT MODIFY THIS CODE
String s = getName() + ": " + getNumAccounts()
+ " of " + getAccounts().length
+ " accounts open";
for (Account account : getAccounts()) {
if (account == null) {
break;
}
s += "\n " + account;
}
return s;
}
}
MainAccount.java
package coe318.lab4;
public class MainAccount {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Account alice = new Account("Alice", 123, 100.00);
Account bob = new Account("Bob", 789, 0);
System.out.println(bob);
System.out.println(alice);
alice.withdraw(15);
System.out.println(alice);
alice.withdraw(200);
System.out.println(alice);
alice.withdraw(-1);
System.out.println(alice);
alice.deposit(150);
alice.withdraw(200);
System.out.println(alice);
bob.deposit(300);
System.out.println(bob);
bob.withdraw(100);
System.out.println(bob);
}
}
MainBank.java
package coe318.lab4;
public class MainBank {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Bank [] banks = {new Bank("Toronto Dominion", 3),
new Bank("Bank of Montreal", 5)};
Bank td = banks[0];
Bank bmo = banks[1];
System.out.println(td);
Account charlie = new Account("Charles", 234, 200.00);
td.add(charlie);
System.out.println(td);
Account dora = new Account("Dora", 456, 300.00);
td.add(dora);
System.out.println("td has account # 456: " +
td.hasAccountNumber(456));
Account ed = new Account("Edward", 456, 400.00);
for(Bank bank : banks) {
if (bank.add(ed)) break;
}
for(Bank bank : banks) {
System.out.println(bank);
}
}
}coe318/lab5/BlackjackGame.java
package coe318.lab5;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author rocky
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class BlackjackGame {
private CardPile deck;
private CardPile houseCards;
private CardPile yourCards;
private boolean houseDone;
private boolean playerDone;
private UserInterface ui;
public BlackjackGame(UserInterface ui) {
this.ui = ui;
ui.setGame(this);
deck = new CardPile();
for (int i = 2; i < 15; i++) {
for (int j = 0; j < 4; j++) {
deck.add(new Card(i, j, true));
}
}
houseCards = new CardPile();
yourCards = new CardPile();
houseDone = false;
playerDone = false;
}
public void start() {
Card c;
c = deck.removeRandom();
c.setFaceUp(false);
getHouseCards().add(c);
getHouseCards().add(deck.removeRandom());
getYourCards().add(deck.removeRandom());
getYourCards().add(deck.removeRandom());
ui.display();
}
public void play() {
while (!houseDone || !playerDone) {
if (!houseDone) {
if (score(getHouseCards()) < 17) {
getHouseCards().add(deck.removeRandom());
// ui.display();
} else {
houseDone = true;
}
}
if (!playerDone) {
if (ui.hitMe()) {
getYourCards().add(deck.removeRandom());
ui.display();
} else {
playerDone = true;
}
}
}
}
y
public void end() {
getHouseCards().getCards().get(0).setFaceUp(true);
ui.gameOver();
}
/**
* Determine the score of a pile of cards.
*
* @param p
* @return the score
*/
public int score(CardPile p) {
int total = 0;
for (Card c : p.getCards()) {
int rank = c.getRank();
if (rank == 14) {
total += 1;
} else if (rank >= 11) {
total += 10;
} else {
total += rank;
}
}
return total;
}
/**
* @return the houseCards
*/
public CardPile getHouseCards() {
return houseCards;
}
/**
* @return the yourCards
*/
public CardPile getYourCards() {
return yourCards;
}
public static void main(String[] args) {
BlackjackGame game = new BlackjackGame(new SimpleUI());
game.start();
game.play();
game.end();
}
}
coe318/lab5/Card.java
package coe318.lab5;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author rocky
*/
public class Card implements Comparable {
//Symbolic constants
public static final int CLUB = 0;
public static final int DIAMOND = 1;
public static final int HEART = 2;
public static final int SPADE = 3;
private final int rank;
private final int suit;
private boolean faceUp;
/**
* Construct a card of the given rank, suit and whether it is faceup or
* facedown. The rank is an integer from 2 to 14. Numbered cards (2 to 10)
* have a rank equal to their number. Jack, Queen, King and Ace have the
* ranks 11, 12, 13, and 14 respectively. The suit is an integer from 0 to 3
* for Clubs, Diamonds, Hearts and Spades respectively.
*
* @param rank
* @param suit
* @param faceUp
*/
public Card(int rank, int suit, boolean faceUp) {
this.rank = rank;
this.suit = suit;
this.faceUp = faceUp;
}
/**
* @return the faceUp
*/
public boolean isFaceUp() {
if (this.faceUp == true) {
return true;
} else {
return false;
}
//FIX THIS
}
/**
* @param faceUp the faceUp to set
*/
public void setFaceUp(boolean faceUp) {
this.faceUp = faceUp;
}
/**
* @return the rank
*/
public int getRank() {
return this.rank; //FIX THIS
}
/**
* @return the suit
*/
public int getSuit() {
return this.suit;//FIX THIS
}
@Override
public boolean equals(Object ob) {
if (!(ob instanceof Card)) {
return false;
}
Card c = (Card) ob;
return (this.getRank() == c.getRank()) && (this.getSuit() == c.getSuit()); //FIX THIS
}
@Override
public int hashCode() {//DO NOT MODIFY
int hash = 7;
hash = 31 * hash + this.getRank();
hash = 31 * hash + this.getSuit();
return hash;
}
@Override
public int compareTo(Object obj) {//DO NOT MODIFY
return compareTo((Card) obj);
}
public int compareTo(Card c) {
if (this.getRank() < c.getRank()) {
return -1;
} else if (this.getRank() > c.getRank()) {
return 1;
} else {
if (this.getSuit() < c.getSuit()) {
return -1;
} else if (this.getSuit() > c.getSuit()) {
return 1;
} else {
return 0;
}
}
//FIX THIS
}
/**
* Return the rank as a String. For example, the 3 of Hearts produces the
* String "3". The King of Diamonds produces the String "King".
*
* @return the rank String
*/
public String getRankString() {
if (this.getRank() <= 10) {
return String.valueOf(this.getRank());
} else if (this.getRank() == 11) {
return "Jack";
} else if (this.getRank() == 12) {
return "Queen";
} else if (this.getRank() == 13) {
return "King";
} else {
return "Ace"; //FIX THIS
}
}
/**
* Return the suit as a String: "Clubs", "Diamonds", "Hearts" or "Spades".
*
* @return the suit String
*/
public String getSuitString() {
if (this.getSuit() == 0) {
return "Clubs";
} else if (this.getSuit() == 1) {
return "Diamonds";
} else if (this.getSuit() == 2) {
return "Hearts";
} else {
return "Spades";
}
//FIX THIS
}
/**
* Return "?" if the card is facedown; otherwise, the rank and suit of the
* card.
*
* @return the String representation
*/
@Override
public String toString() {
if (this.faceUp == false) {
return "?";
} else {
return this.getRankString() + " of " + this.getSuitString();
}
//FIX THIS
}
public static void main(String[] args) {
//Create 5 of clubs
Card club5 = new Card(5, 0, true);
System.out.println("club5: " + club5);
Card spadeAce = new Card(14, SPADE, true);
System.out.println("spadeAce: " + spadeAce);
System.out.println("club5 compareTo spadeAce: "
+ club5.compareTo(spadeAce));
System.out.println("club5 compareTo club5: "
+ club5.compareTo(club5));
System.out.println("club5 equals spadeAce: "
+ club5.equals(spadeAce));
System.out.println("club5 equals club5: "
+ club5.equals(club5));
}
}
coe318/lab5/CardPile.java
package coe318.lab5;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author rocky
*/
import java.util.ArrayList;
/**
* A pile of cards.
*
*/
public class CardPile {
//Instance variables
private ArrayList<Card> cards;
public CardPile() {
//Initialize the instance variable.
cards = new ArrayList<Card>();
}
/**
* Add a card to the pile.
*
* @param card
*/
public void add(Card card) {
cards.add(card);
//FIX THIS
}
/**
* Remove a card chosen at random from the pile.
*
* @return
*/
public Card removeRandom() {
int index = (int) (Math.random() * cards.size());
return cards.remove(index); //FIX THIS
}
/**
* The string representation is a space separated list of each card.
*
* @return
*/
@Override
public String toString() {
//FIX THIS
String list = "";
for (int i = 0; i < cards.size(); i++) {
list += cards.get(i).toString();
list +="\n";
}
return list;
}
/**
* @return the cards
*/
public ArrayList<Card> getCards() {
return cards;
}
public static void main(String[] args) {
CardPile p = new CardPile();
p.add(new Card(2, 1, true));
p.add(new Card(3, 2, true));
p.add(new Card(4, 3, false));
p.add(new Card(14, 1, true));
System.out.println("Removed: " + p.removeRandom());
System.out.println("Removed: " + p.removeRandom());
System.out.println("Removed: " + p.removeRandom());
System.out.println("Removed: " + p.removeRandom());
System.out.println("");
CardPile deck = new CardPile();
for (int i = 2; i < 15; i++) {
for (int j = 0; j < 4; j++) {
deck.add(new Card(i, j, true));
}
}
for (int i = 0; i < 52; i++) {
System.out.println((i + 1) + ": " + deck.removeRandom());
}
}
}
coe318/lab5/SimpleUI.java
package coe318.lab5;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author rocky
*/
import java.util.Scanner;
public class SimpleUI implements UserInterface {
private BlackjackGame game;
private Scanner user = new Scanner(System.in);
@Override
public void setGame(BlackjackGame game) {
this.game = game;
}
/**
* Print a heading followed by one card per line. CardPile.toString()
* already ends every card with a newline, so print (not println) it.
*/
private void show(String heading, CardPile pile) {
System.out.println(heading);
System.out.print(pile);
}
@Override
public void display() {
show("House holds:", game.getHouseCards());
System.out.println();
show("You hold:", game.getYourCards());
System.out.println();
}
@Override
public boolean hitMe() {
System.out.print("Do you want another card (y/n)? ");
String answer = user.nextLine();
return answer.trim().equalsIgnoreCase("y");
//FIX THIS
}
@Override
public void gameOver() {
int houseScore = game.score(game.getHouseCards());
int yourScore = game.score(game.getYourCards());
System.out.println("Game over");
System.out.println();
show("House holds:", game.getHouseCards());
System.out.println();
show("You hold:", game.getYourCards());
System.out.println();
System.out.println("Your score: " + yourScore + ", House score: " + houseScore);
if (yourScore > 21) {
System.out.println("You bust. House wins.");
} else if (houseScore > 21) {
System.out.println("House busts. You win!");
} else if (yourScore > houseScore) {
System.out.println("You win!");
} else if (houseScore > yourScore) {
System.out.println("House wins.");
} else {
System.out.println("Tie. House wins.");
}
}
}
coe318/lab5/UserInterface.java
package coe318.lab5;
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
*/
/**
*
* @author rocky
*/
public interface UserInterface {//DO NOT MODIFY
/** Set the Blackjack game
* this UserInterface belongs to.
* @param game
*/
public void setGame(BlackjackGame game);
/**
* Display the cards held by the House
* and the player (you).
*/
public void display();
/**
* Prompt the user if they want another
* card. Return true if another card
* desired.
* @return
*/
public boolean hitMe();
/**
* Display the final cards, scores
* and winner.
*/
public void gameOver();
}
lab6/shipment/ExpressParcel.java
package lab6.shipment;
class ExpressParcel extends StandardParcel {
private final boolean sameDay;
public ExpressParcel(double weightKg, double distanceKm, boolean insured, String sizeTier, boolean sameDay) {
//TO DO: Complete the constructor
super(weightKg, distanceKm, insured, sizeTier);
this.sameDay = sameDay;
}
@Override
public double shippingCost() {
// Build on Standard cost using super.<method>()
double cost = super.shippingCost();
// Express surcharge: faster delivery multiplier + optional same-day fee
cost *= 1.35; // express speed premium
//TO DO update cost based on sameDay
if (sameDay) {
cost += 7.50;
}
return cost;
}
}lab6/shipment/InternationalParcel.java
package lab6.shipment;
public class InternationalParcel extends Parcel {
private final String region; // e.g., "EU", "APAC", "NA"
private final double customsRate; // 0.0 - 0.25 (percentage of base as duties)
public InternationalParcel(double weightKg, double distanceKm, boolean insured,
String region, double customsRate) {
super(weightKg, distanceKm, insured);
if (customsRate < 0 || customsRate > 0.25) {
throw new IllegalArgumentException("customsRate must be between 0.0 and 0.25");
}
this.region = region;
this.customsRate = customsRate;
}
@Override
public double shippingCost() {
//TO DO complete this part
double base = super.shippingCost();
double crossBorderFee = 8.00;
double customsDuty = customsRate * base;
return base + crossBorderFee + customsDuty;
}
}
lab6/shipment/Main.java
package lab6.shipment;
public class Main {
public static void main(String[] args) {
Parcel[] parcels = new Parcel[] {
new StandardParcel(2.0, 120, true, "M"),
new ExpressParcel(1.0, 40, false, "S", true),
new InternationalParcel(3.2, 800, true, "EU", 0.12),
};
for (Parcel p : parcels) {
System.out.printf(" Cost: $%.2f%n", p.shippingCost());
}
}
}
lab6/shipment/Parcel.java
package lab6.shipment;
public class Parcel {
protected final double weightKg;
protected final double distanceKm;
protected final boolean insured;
public Parcel(double weightKg, double distanceKm, boolean insured) {
if (weightKg <= 0 || distanceKm < 0) {
throw new IllegalArgumentException("Weight must be > 0 and distance >= 0");
}
this.weightKg = weightKg;
this.distanceKm = distanceKm;
this.insured = insured;
}
public double shippingCost() {
// Base: weight + distance, with small base fee
double base = 3.50 + (weightKg * 1.20) + (distanceKm * 0.05);
if (insured) base += Math.max(1.50, 0.02 * base);
return base;
}
}lab6/shipment/StandardParcel.java
package lab6.shipment;
class StandardParcel extends Parcel {
// sizeTier: S/M/L affects handling
protected final String sizeTier;
public StandardParcel(double weightKg, double distanceKm, boolean insured, String sizeTier) {
super(weightKg, distanceKm, insured);
if (!sizeTier.matches("[SML]")) {
throw new IllegalArgumentException("sizeTier must be S, M, or L");
}
this.sizeTier = sizeTier;
}
@Override
public double shippingCost() {
double cost = super.shippingCost();
double handling= 0;
//TO DO
//Write lines of codes that calculates handeling based on sizeTier
if (sizeTier.equals("S")) {
handling = 0.75;
} else if (sizeTier.equals("M")) {
handling = 1.25;
} else if (sizeTier.equals("L")) {
handling = 1.75;
}
return cost + handling;
}
}
Car.java
public class Car extends Vehicle {
private boolean automatic;
public Car(String plateNumber, String model, int year, boolean automatic) {
// TO DO
super(plateNumber, model, year);
this.automatic = automatic;
}
public boolean isAutomatic() {
return automatic;
}
// Overriding toString
@Override
public String toString() {
return "Car: " + super.toString() +
(automatic ? " [Automatic]" : " [Manual]");
}
@Override
public double calculateRentalPrice(int days) {
//TO DO. complete the code such that Dayli Rate for automatic cars are 65.0 an for non automatic cars are 55.0.
if(automatic){
return (days * 65.0);
}else{
return (days * 55.0);
}
}
@Override
public double calculateInsurancePremium(int days) {
// TO DO. complete the code, such taht daily insurence date to be the vehicle’s base, increased by 10%
return super.getBaseInsuranceRate() * 1.1 * days;
}
// Overloaded version with GPS option
public double calculateRentalPrice(int days, boolean gpsIncluded) {
double base = calculateRentalPrice(days);
if (gpsIncluded) {
base += 10.0 * days; // GPS daily fee
}
return base;
}
// Static method HIDING superclass static method
public static void printVehicleType() {
System.out.println("Car");
}
}
Insurable.java
public interface Insurable {
double calculateInsurancePremium(int days);
}
Rentable.java
public interface Rentable {
double calculateRentalPrice(int days);
void startRental();
void endRental();
}
RentalContract.java
public class RentalContract {
private Rentable rentable;
private int days;
private boolean insuranceAdded;
public RentalContract(Rentable rentable, int days, boolean insuranceAdded) {
this.rentable = rentable;
this.days = days;
this.insuranceAdded = insuranceAdded;
}
public double calculateTotalPrice() {
double basePrice = rentable.calculateRentalPrice(days);//To DO. Complete this line of the code, such that the baseprice is found.
double insurance = 0.0;
if (insuranceAdded ) {
insurance = ((Insurable) rentable).calculateInsurancePremium(days);
}
return basePrice + insurance;
}
public void printSummary() {
System.out.println("=== Rental Contract Summary ===");
System.out.println("Vehicle type: " + rentable.getClass().getSimpleName());
System.out.println("Days: " + days);
System.out.println("Insurance added: " + insuranceAdded);
System.out.println("Total price: " + calculateTotalPrice());
System.out.println("===============================");
}
}
RentalService.java
public class RentalService {
public static void log(String message) {
System.out.println("[INFO] " + message);
}
public static void log(String message, int severity) {
System.out.println("[SEVERITY " + severity + "] " + message);
}
public void processRental(Rentable rentable, int days) {
log("Processing rental for " + rentable.getClass().getSimpleName());
rentable.startRental();
double price = rentable.calculateRentalPrice(days);
System.out.println("Base rental price for " + days + " days: " + price);
rentable.endRental();
System.out.println();
}
public static void main(String[] args) {
Car honda21 = new Car("XYZ-456", "Honda Civic", 2021, false);
double priceNoGps = honda21.calculateRentalPrice(3);
double priceWithGps = honda21.calculateRentalPrice(3, true);
System.out.println("Car price without GPS: " + priceNoGps);
System.out.println("Car price with GPS: " + priceWithGps);
Rentable car = new Car("ABC-123", "Toyota Corolla", 2020, true);
Rentable truck = new Truck("TRK-999", "Volvo FH", 2019, 12.0);
Rentable luxuryCar = new Car("LUX-777", "BMW 7 Series", 2023, true);
RentalService service = new RentalService();
service.processRental(car, 3);
service.processRental(truck, 2);
service.processRental(luxuryCar, 1);
service.processRental(honda21, 1);
RentalContract contract1 = new RentalContract(car, 4, true);
contract1.printSummary();
RentalContract contract2 = new RentalContract(luxuryCar, 2, true);
contract2.printSummary();
Vehicle.printVehicleType();
Car.printVehicleType();
Truck.printVehicleType();
honda21.printPlate();
}
}
Truck.java
public class Truck extends Vehicle {
private double loadCapacityInTons;
public Truck(String plateNumber, String model, int year, double loadCapacityInTons) {
//TO DO
super(plateNumber, model, year);
this.loadCapacityInTons = loadCapacityInTons;
}
public double getLoadCapacityInTons() {
return loadCapacityInTons;
}
@Override
public String toString() {
return "Truck: " + super.toString() +
" [Capacity: " + loadCapacityInTons + " tons]";
}
@Override
public double calculateRentalPrice(int days) {
// TO DO when a daily rate starts at 90 dollars and increases by 10 dollars for each ton of load capacity.
return days * (90.0 + 10.0*this.loadCapacityInTons);
}
@Override
public double calculateInsurancePremium(int days) {
// TO Do: the daily rate is the base insurance rate increased by 50 percent
return super.getBaseInsuranceRate() * 1.5 * days;
}
public static void printVehicleType() {
System.out.println("Truck");
}
}
Vehicle.java
public class Vehicle implements Insurable, Rentable {
private String plateNumber;
private String model;
private int year;
final private double DefaultRentPrice=100;
public Vehicle(String plateNumber, String model, int year) {
this.plateNumber = plateNumber;
this.model = model;
this.year = year;
}
public String getPlateNumber() {
return plateNumber;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public String toString() {
return year + " " + model + " (" + plateNumber + ")";
}
@Override
public double calculateRentalPrice(int days){
return(DefaultRentPrice*days);
}
@Override
public double calculateInsurancePremium(int days) {
return getBaseInsuranceRate() * days;
}
@Override
public void startRental() {
System.out.println("Starting rental for " + this.toString());
}
@Override
public void endRental() {
System.out.println("Ending rental for " + this.toString());
}
public final double getBaseInsuranceRate() {
return 20.0;
}
public final void printPlate() {
System.out.println("Plate: " + plateNumber);
}
public static void printVehicleType() {
System.out.println("Generic Vehicle");
}
}
coe318/lab7/Circuit.java
package coe318.lab7;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A circuit made of any number of components, kept in the order they were
* added.
*
* @author rocky
*/
public class Circuit {
private final ArrayList<Component> components;
/**
* Creates an empty circuit.
*/
public Circuit() {
components = new ArrayList<>();
}
/**
* Adds a component to the circuit.
*
* @param component the component to add
* @throws IllegalArgumentException if component is null
*/
public void add(Component component) {
if (component == null) {
throw new IllegalArgumentException("Component cannot be null");
}
components.add(component);
}
/**
* Returns the number of components in the circuit.
*
* @return the number of components
*/
public int size() {
return components.size();
}
/**
* Returns the components in the order they were added.
*
* @return a read-only list of the components
*/
public List<Component> getComponents() {
return Collections.unmodifiableList(components);
}
/**
* Returns the SPICE description of the circuit. Components are listed in
* the order they were added, and each kind is numbered on its own
* (V1, R1, V2, R2, R3, ...).
*
* @return the SPICE lines separated by newlines, or an empty string if the
* circuit has no components
*/
public String toSpice() {
Map<String, Integer> counts = new HashMap<>();
StringBuilder sb = new StringBuilder();
for (Component c : components) {
String prefix = c.getSpicePrefix();
int number = counts.getOrDefault(prefix, 0) + 1;
counts.put(prefix, number);
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(c.toSpice(number));
}
return sb.toString();
}
}
coe318/lab7/Component.java
package coe318.lab7;
/**
*
* @author rocky
*/
public abstract class Component {
private final int node1;
private final int node2;
private final double value;
/**
* Creates a component connected between two nodes.
*
* @param node1 the first node
* @param node2 the second node
* @param value the component's value
* @throws IllegalArgumentException if a node is negative, both nodes are
* the same, or the value is not a finite number
*/
protected Component(int node1, int node2, double value) {
if (node1 < 0 || node2 < 0) {
throw new IllegalArgumentException("Node numbers must be 0 or greater");
}
if (node1 == node2) {
throw new IllegalArgumentException("A component must connect two different nodes");
}
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("The value must be a finite number");
}
this.node1 = node1;
this.node2 = node2;
this.value = value;
}
/**
* Returns the first node this component is connected to.
* @return the first node
*/
public int getNode1() {
return node1;
}
/**
* Returns the second node this component is connected to.
* @return the second node
*/
public int getNode2() {
return node2;
}
/**
* Returns the value of this component.
* @return the value (Ohms for a resistor, Volts for a voltage source)
*/
public double getValue() {
return value;
}
/**
* Returns the uppercase letter SPICE uses for this component, (ex. "R" for a resistor.)
* @return the SPICE prefix letter
*/
public abstract String getSpicePrefix();
/**
* Returns how the value is written in a SPICE line.
* @return the value part of the SPICE line
*/
protected String spiceValue() {
return String.valueOf(value);
}
/**
* Returns the SPICE description of this component, (ex. @code R2 2 3 0.5}.
* @param number the component's number among components of the same kind (1, 2, 3, etc.)
* @return one line of SPICE (without a line terminator)
*/
public String toSpice(int number) {
return getSpicePrefix() + number + " " + node1 + " " + node2 + " " + spiceValue();
}
}
coe318/lab7/Resistor.java
package coe318.lab7;
/**
* A resistor. Resistors are not polarized, so the order of the two nodes
* does not matter.
*
* @author rocky
*/
public class Resistor extends Component {
/**
* Creates a resistor connected between two nodes.
*
* @param node1 one node
* @param node2 the other node
* @param resistance the resistance in Ohms (must be greater than 0)
* @throws IllegalArgumentException if the resistance is not greater than
* 0, or the nodes are invalid
*/
public Resistor(int node1, int node2, double resistance) {
super(node1, node2, resistance);
if (!(resistance > 0)) {
throw new IllegalArgumentException("Resistance must be greater than 0");
}
}
/**
* Returns the resistance.
*
* @return the resistance in Ohms
*/
public double getResistance() {
return getValue();
}
/**
* Returns "R", the SPICE letter for a resistor.
*
* @return "R"
*/
@Override
public String getSpicePrefix() {
return "R";
}
}
coe318/lab7/UserMain.java
package coe318.lab7;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Reads a circuit description from standard input, one command per line, and
* interprets it.
* @author rocky
*/
public class UserMain {
private final Circuit circuit;
private final PrintStream out;
/**
* Creates an interpreter that builds a new, empty circuit.
* @param out where output (SPICE listings, messages) is printed
*/
public UserMain(PrintStream out) {
this.circuit = new Circuit();
this.out = out;
}
/**
* Returns the circuit built so far.
* @return the circuit
*/
public Circuit getCircuit() {
return circuit;
}
/**
* Interprets one line of input.
* @param line one line of input
* @return false if the line was the end command (stop reading), true
* otherwise
*/
public boolean processLine(String line) {
String trimmed = line.trim();
if (trimmed.isEmpty()) {
return true;
}
String[] tokens = trimmed.split("\\s+");
String command = tokens[0].toLowerCase();
switch (command) {
case "end":
out.println("All Done");
return false;
case "spice":
String spice = circuit.toSpice();
if (!spice.isEmpty()) {
out.println(spice);
}
return true;
case "r":
case "v":
addComponent(command, tokens, trimmed);
return true;
default:
out.println("Error: unknown command: " + trimmed);
return true;
}
}
/**
* Parses an "r" or "v" line and adds the component to the circuit.
* @param command "r" or "v"
* @param tokens the line split into words
* @param line the whole line, used in error messages
*/
private void addComponent(String command, String[] tokens, String line) {
if (tokens.length != 4) {
out.println("Error: expected \"" + command + " node1 node2 value\": " + line);
return;
}
try {
int node1 = Integer.parseInt(tokens[1]);
int node2 = Integer.parseInt(tokens[2]);
double value = Double.parseDouble(tokens[3]);
if (command.equals("r")) {
circuit.add(new Resistor(node1, node2, value));
} else {
circuit.add(new VoltageSource(node1, node2, value));
}
} catch (NumberFormatException e) {
out.println("Error: nodes must be whole numbers and the value a number: " + line);
} catch (IllegalArgumentException e) {
out.println("Error: " + e.getMessage() + ": " + line);
}
}
/**
* Reads lines from the scanner until the end command or the end of input.
*
* @param in the source of input lines
*/
public void run(Scanner in) {
while (in.hasNextLine()) {
if (!processLine(in.nextLine())) {
return;
}
}
}
/**
* Reads and interprets commands from stdin.
* @param args not used
*/
public static void main(String[] args) {
new UserMain(System.out).run(new Scanner(System.in));
}
}
coe318/lab7/VoltageSource.java
package coe318.lab7;
/**
* A DC voltage source.
* @author rocky
*/
public class VoltageSource extends Component {
/**
* Creates a DC voltage source.
*
* @param positiveNode the node connected to the positive side
* @param negativeNode the node connected to the negative side
* @param voltage the voltage in Volts (may be zero or negative)
* @throws IllegalArgumentException if the nodes are invalid
*/
public VoltageSource(int positiveNode, int negativeNode, double voltage) {
super(positiveNode, negativeNode, voltage);
}
/**
* Returns the voltage.
* @return the voltage in Volts
*/
public double getVoltage() {
return getValue();
}
/**
* Returns "V", the SPICE letter for a voltage source.
* @return "V"
*/
@Override
public String getSpicePrefix() {
return "V";
}
/**
* Returns the value with the DC keyword in front, as SPICE expects.
* @return for example "DC 2.0"
*/
@Override
protected String spiceValue() {
return "DC " + super.spiceValue();
}
}
test/coe318/lab7/CircuitTest.java
package coe318.lab7;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* JUnit tests for the Circuit class.
*
* @author rocky
*/
public class CircuitTest {
/**
* Creates the test class.
*/
public CircuitTest() {
}
/**
* A new circuit has no components and an empty SPICE listing.
*/
@Test
public void testEmptyCircuit() {
Circuit c = new Circuit();
assertEquals(0, c.size());
assertEquals("", c.toSpice());
}
@Test
public void testAddAndSize() {
Circuit c = new Circuit();
Resistor r = new Resistor(1, 2, 0.25);
VoltageSource v = new VoltageSource(1, 0, 2.0);
c.add(v);
c.add(r);
assertEquals(2, c.size());
assertSame(v, c.getComponents().get(0));
assertSame(r, c.getComponents().get(1));
}
@Test(expected = IllegalArgumentException.class)
public void testAddNull() {
new Circuit().add(null);
}
@Test
public void testToSpiceHandoutExample() {
Circuit c = new Circuit();
c.add(new VoltageSource(1, 0, 2.0));
c.add(new Resistor(1, 2, 0.25));
c.add(new VoltageSource(2, 0, 3));
c.add(new Resistor(2, 3, 0.5));
c.add(new Resistor(3, 0, 1.0));
String expected = "V1 1 0 DC 2.0\n"
+ "R1 1 2 0.25\n"
+ "V2 2 0 DC 3.0\n"
+ "R2 2 3 0.5\n"
+ "R3 3 0 1.0";
assertEquals(expected, c.toSpice());
// Calling it again gives the same numbering.
assertEquals(expected, c.toSpice());
}
@Test
public void testToSpiceKeepsPolarity() {
Circuit c = new Circuit();
c.add(new VoltageSource(0, 1, -2.0));
assertEquals("V1 0 1 DC -2.0", c.toSpice());
}
@Test(expected = UnsupportedOperationException.class)
public void testGetComponentsIsReadOnly() {
Circuit c = new Circuit();
c.getComponents().add(new Resistor(1, 0, 1.0));
}
}
test/coe318/lab7/ResistorTest.java
package coe318.lab7;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* JUnit tests for the Resistor class.
*
* @author rocky
*/
public class ResistorTest {
/**
* Creates the test class.
*/
public ResistorTest() {
}
@Test
public void testGetters() {
Resistor r = new Resistor(2, 3, 5.2);
assertEquals(2, r.getNode1());
assertEquals(3, r.getNode2());
assertEquals(5.2, r.getResistance(), 1e-12);
assertEquals(5.2, r.getValue(), 1e-12);
}
@Test
public void testToSpice() {
Resistor r = new Resistor(2, 3, 5.2);
assertEquals("R4 2 3 5.2", r.toSpice(4));
assertEquals("R", r.getSpicePrefix());
}
@Test(expected = IllegalArgumentException.class)
public void testZeroResistance() {
new Resistor(1, 2, 0);
}
@Test(expected = IllegalArgumentException.class)
public void testNegativeResistance() {
new Resistor(1, 2, -1.0);
}
@Test(expected = IllegalArgumentException.class)
public void testNegativeNode() {
new Resistor(-1, 2, 1.0);
}
@Test(expected = IllegalArgumentException.class)
public void testSameNode() {
new Resistor(2, 2, 1.0);
}
}