Thursday, April 26, 2012

Challenge 054

ClassCastException occurs when you attempt to cast an object of one data type to another type. Also, calling an object to a subclass of which it is not an instance.


(A) ((SavingsAccount) b).addInterest(); Does not match because b refers to BankAccount not SavingsAccount

(B) ((CheckingAccount) b).withdraw(200); Does not match because b refers to BankAccount not CheckingAccount

(C) ((CheckingAccount) c).deposit(800); Is the only one of the five statements that works because c refers to CheckingAccount and the statement is calling for a deposit in CheckingAccount

(D) ((CheckingAccount) s).withdraw(150); Does not match because s refers to SavingsAccount not CheckingAccount

(E) ((SavingsAccount) c).addInterest(); Does not match because c refers to CheckingAccount not SavingsAccount


(Does not match means it does not match with the subclass)

Nick Armold helped me with this challenge

Thursday, March 22, 2012

challenge 052

The first statement is true due to high-order inheritance. SmartPlayer implements the Player interface because HumanPlayer implements the interface which has SmartPlayer as a subclass, therefore being implemented with HumanPlayer due to inheritance.

The second statement is also true because HumanPlayer implements the interface Player. Player contains the methods int getMove() and void updateDisplay() and you stated that HumanPlayer implements the Player interface, so it also inherits the two methods within the class.

The third statement is false. You are able to declare a reference of type Player because HumanPlayer and SmartPlayer share the Player interface. To reference variables, the types need to share a superclass or interface, which they do (Player interface). Player can therefore be referenced because Player also refers to HumanPlayer and SmartPlayer and is in the Player interface.
(I used the following website to help me understand more about referencing:
http://stackoverflow.com/questions/4207732/how-to-declare-object-reference-variables-and-assign-them-values-according-to-us)

The fourth statement is true because in inheritance, a method that is declared can be overridden by any class that extends the primary class. SmartPlayer inherits the Player interface and its components and is able to alter/override any method.

The fifth statement is true because any interface that has the capability of being referenced can hold a parameter. Since HumanPlayer and SmartPlayer inherit the Player interface, it can take parameters for the HumanPlayer and SmartPlayer method.

Wednesday, March 21, 2012

Challenge 039

Statement I is incorrect because the super class that will be inherited does not contain any parameters. You know this because super(); contains nothing within the parenthesis (no parameters). However, the Hen class has the parameter(String species).

Statement II is the only correct statement because it contains super which allows the class to be inherited, and it contains the parameter inside the inherited class which is a string value, "species".

Statement III is incorrect because mySpecies = species is simply the Bird class' constructor which is a private instance variable, therefore making it impossible to reach.

Challenge 048

I       s1 == s2              false
II      s1.equals(s2)       true
III     s3.equals(s2)       true

Statement I is false because == is an operator that means the two objects have equality to one another. However, the objects are not the same (s1 and s2 are two separate unequal objects).

Statement II is true because equals refers to the values of the two objects being equal. This is the case because they both have the String value "crab, they are simply stated in two different ways

Statement III is true because s3(= s1) does equal s2(new String("crab"). The values are the same (String "crab"). However if it were stated: s3 == s2, it would have been false because s3 and s2 are two different objects.


The following website explains the == operator:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Challenge 049


import java.lang.Math;

public class Circle extends Shape
{
    private double radius;
   
    public Circle(String name, double r)
    {
        super(name);
        radius = r;
    }

    public double area()
    {
        return (Math.PI * radius * radius);
    }
    //Nick Armold helped me with the Math.PI
    //area for a circle = (pi)r^2)
    public double perimeter()
    {
        return (2 * Math.PI * radius);
    }
    //formula for perimeter is 2x(pi)x(r)
}

public class Square extends Shape
{
    private double length;
   
    public Square(String name, double s)
   
    {
        super(name);
        length = s;
    }
   
    public double area();
    {
        return (side * side);
    }
    //formula for area
    public double perimeter();
    {
        return (4 * side);
    }
    //formula for perimeter
}  
//Nick Armold helped me with this challenge

Wednesday, March 14, 2012

Challenge 045: Whaddup Gridworld???


import info.gridworld.actor.Actor;
import info.gridworld.actor.Rock;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;

public class RollingStone extends Rock
{
    public RollingStone()
    {
        super();
        setDirection(90);
    }
   
    public void act ()
    {
        if (canMove())
            move();
        else
            turn();
    }
   
    public void turn()
    {
        setDirection(getDirection() + Location.HALF_CIRCLE);
    }
   
    public void move ()
    {
        Grid<Actor> gr = getGrid();
       
        if (gr == null)
            return;
       
        Location loc = getLocation();
        Location next = loc.getAdjacentLocation(getDirection());
       
        Actor neighbor = gr.get(next);
       
        if (neighbor != null)
            neighbor.removeSelfFromGrid();
       
        if (gr.isValid(next))
            moveTo(next);
           
            else
                removeSelfFromGrid();
    }
   
    public boolean canMove()
    {
        Grid<Actor> gg = getGrid();
       
        if(gg == null)
            return false;
           
        Location last = getLocation();
        Location next = last.getAdjacentLocation(getDirection());
       
        Actor neighbor = gg.get(next);
            return true;
       
    }
}      

Monday, March 5, 2012

Challenge 044: Variety is the Spice of Life


for loop:

int sum = 0;
for (int index = 0; index < arr.length; index++)

{
    sum += arr[index];
}


for-each loop:

int sum =0;
for (int index:arr)

{
    sum += index;
}

I also referenced the following link:

http://forums.devarticles.com/java-development-38/java-changing-while-loop-to-for-loop-169122.html

Challenge 042: Is There A Curve?


import java.util.Scanner;
import java.util.Arrays;

public class IsThereACurve
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
            System.out.print(" # of Students ");
            int n = scan.nextInt();
        int [] scores = new int[n];
        for ( int i = 0; i < scores.length; i++)
       
        {
            System.out.println( "Score: " + (i + 1));
            scores[i] = scan.nextInt();
        }
       
        Arrays.sort(scores);
        System.out.println("Current Score: ");
        for(int x = 0; x <= scores.length - 1; x++)
       
        {
            System.out.println(scores[x]);
        }  
       
        System.out.println();
        curvedScores(scores);
    }
    public static void curvedScores(int [] s)
    {
        int[] newScores = s;
        Arrays.sort(newScores);
        int curve = 100 - newScores [newScores.length - 1];
       
        System.out.println("Curved Scores:");
       
        for(int x = 0; x <= s.length - 1; x++)
       
        {
            System.out.println((s[x] + curve));
        }
    }
}  

Tuesday, February 28, 2012

Challenge 041



public class BankAccount
{
    public double balance;
   
    public BankAccount() {
       
        balance = 0;
       
    }
    public BankAccount(double start)
    {
        balance = start;
    }
    public void Deposit(double amount)
    {
        balance += amount;
        System.out.println("Current balance: $" + balance);
    }
    public void Withdrawl(double amount)
    {
        if(balance >= balance)
        {
            balance -= amount;
            System.out.println("Current balance: $" + balance);
        }
            else
            {
                System.out.println("Insufficient Funds");
            }
    }
    public double getBalance()
    {
        return balance;
    }
}





public class SavingsAccount extends BankAccount
{
    public double interestRate;
    public SavingsAccount(double rate, double start)
    {
        super(start);
        interestRate = rate;
    }
    public double compInterestRate()
    {
        return balance = (balance * interestRate);
    }
}




public class CheckingAccount extends BankAccount
{
    public double minBalance;
    public double fee;
    public CheckingAccount()
    {
    }
   
    public CheckingAccount(double start)
    {
        super(start);
        minBalance = 50.0;
        fee = 2.0;
    }
    public double makeWithdraw(double amount)
    {
        balance -= amount;
        if (balance < minBalance)
        {
            System.out.print("$2.0 fee will be charged due to overdrawing" + (balance + fee));
        }
            else
            {
                System.out.print("Current balance: $" + balance);
            }
        }      
    }      

Tuesday, January 17, 2012

Challenge 033: Ticket Machine


import java.util.Scanner;


public class TicketMachine
{
    // instance variables
    private int price;
    private int balance;
    private int total;
   

    /**
     * Constructor for objects of class challenge033
     * Price = cost of ticket
     * Balance = amount customer puts in
     * Total = total money ticket machine collects
     */
    public TicketMachine(int price)
    {
        // initialise instance variables
        this.price = price;
        this.balance = 0;
        this.total = 0;
    }
    /*
     * Allows customer to see price per ticket
     */
    public void getPrice()
    {
        System.out.println("The Price for one Ticket will be: " + price + " cents\n");
    }
    /*
     * Allows customer to see his current balance
     */
    public void getBalance()
    {
        System.out.println("Balance: " + balance + " cents\n");
    }  
    /*
     * Tells customer to insert money
     */
    public void insertMoney ()
    {
       
        Scanner input = new Scanner(System.in);
        System.out.print("\n");
        /*
         * The utility scanner breaks input into tokens. The tokens are then converted into values of
         * different types. For example a code can allow the user to read a number.
         */
        {
            System.out.println();
            System.out.println("Balance: " + balance + " cents");
            System.out.println("Put Your Money In Me: ");
            int userInput = input.nextInt();
           
            if (userInput > 0)
            {
                balance = balance + userInput;
                System.out.println();
                System.out.println("Your new Balance is: " + balance + " cents");
            }
           
            else
            {
                System.out.println();
                System.out.println("Insert Money Now");
                System.out.println("Click Refund to Receive Money");
            }
         
        }
    }
   
    public void refundBalance()
    {
        if (balance > price)
            System.out.println("Your Change: " + balance + " cents");
            balance = 0;
        }
    /*
     * This allows the customer to remove money if they wish to do so and also gives the costumer his
     * change while returning the balance to 0.
     */
    public void printTicket()
    {
        if(balance >= price)
        {
            System.out.println();
            System.out.println("Purchase Successful");
            System.out.println("--------------------------------");
            System.out.println("Greenman Transit Lines");
            System.out.println("Price: " + price + " cents");
            System.out.println("--------------------------------");
                /*
                 * This shows how the ticket will look when printed
                 */
            total = total + price;
            /*
             * This allows the machine to keep track of amount of money made becuase it takes the
             * previous value and add the cost of a new ticket each time a customer buys one.
             */
            balance = balance - price;
            /*
             * This allows the machine to return the costumer's change if he put too much money in.
             */
        }
        else
        {
            System.out.println();
            System.out.println("Insufficient Funds");
            System.out.println("Please insert " + (price - balance) + " cents.");
            /*
             * This tells the costumer that he is trying to but a ticket but does not have enough money,
             * therefore it does not print.
             */
        }
    }
}