Sunday, October 16, 2011

Class definition to represent playing cards


Problem:

Implement a new class called Card that includes the following entries:
* Named constants for the four suits (CLUBS, DIAMONDS, HEARTS, SPADES) and the four ranks that are traditionally represented in words (ACE, JACK, QUEEN, KING). The values of the rank constants should be 1, 11, 12, and 13, respectively.
* A constructor that takes a rank and a suit and returns a Card with those values. • Accessor methods getRank and getSuit to retrieve the rank and suit components
of a card.
* An implementation of the toString method that returns the complete name of the card as in exercise 1. Remember that you can use the + operator to connect the different parts of the string together, as shown in the toString implementation for the Rational class in Figure 6-9.

Roberts ch 6, problem 7.

/* File: Card class
 * ----------------------------
 * Class to represent a playing card. There are named constants for suit and face card values to translate integers into respective values,
 * so a client of this class can represent this information with either the integer or the constant.
 * 
 * How you'd use this class:
 * a) Create a new playing card: "myCard = new Card (12, 2)" or "myCard = new Card (Card.QUEEN, Card.HEARTS)"
 * b) Get the rank or suit of cards: "myCardSuit = myCard.getSuit()" or "myCardRank = myCard.getRank()"
 */

public class Card {
    
    public Card (int rank, int suit){ //Constructor
        cardRank = rank; // A real program would check whether "rank" is between 1 and 13, and if not, raise an illegal arguments exception
        cardSuit = suit; // A real program would check whether "rank" is between 1 and 4, and if not, raise an illegal arguments exception
    }
 
    public String getRank() {
        switch (cardRank) {
            case ACE: return "Ace";
            case JACK: return "Jack";
            case QUEEN: return "Queen";
            case KING: return "King";
            default: return Integer.toString(cardRank); 
        }
    }
   
    public String getSuit() {
        switch (cardSuit) {
            case SPADES: return "Spades";
            case HEARTS: return "Hearts";
            case CLUBS: return "Clubs";
            case DIAMONDS: return "Diamonds";
            default: return "no suit."; // Won't actually happen but Java needs it or it thinks the switch statement is incomplete
        }
    }
    
    public String toString() {
        return ("The" + getRank() + " of " + getSuit() + ".");
    }
    
    // Instance variables keep track of the suit and rank values for the lifetime of the card object
    private int cardSuit; // Keeps track of the Card object's suit
    private int cardRank; // Keeps track of the object's rank
    
    // Named Constants to establish int values for each of the suits -- Static variables are class variables
    public static final int SPADES = 1; //does this need to be "void"...?
    public static final int HEARTS = 2;
    public static final int CLUBS = 3;
    public static final int DIAMONDS = 4;
  
    // Named constants to establish int values for each of the suits 
    public static final int ACE = 1; //How does this named constant interact w/ the rest of the program? This part is a little messed up
    public static final int JACK = 11;
    public static final int QUEEN = 12;
    public static final int KING = 13;
}
This problem came before the "Employee" class problem in the book, but I definitely think it's more confusing than writing the Employee class and only really understood it after doing problem 8. At heart, the main point of both classes is to store information about an employee instance or playing card instance and let clients of the class access the information via public methods.

This one had an extra wrench thrown in because we needed to associate integers with suit or facecard values. I completed the class definition and I get now that the benefit of having the named constants is that, even though the constructor method is expecting integers for the suit and number values, you can pass the constants instead so it's a bit more human-readable.

For example, suit information for any particular card is represented in four different places:
1) In the constructor method, the client passes the suit value through as a parameter that instantly gets stored to the instance variable.
2) The instance variable that keeps track of the suit for the lifetime of the object
3) The named constants series translates suit integers into strings. ** Question: Why do we have this level of translation instead of having the constructor look for a string instead of an integer for the "suit" argument? ** From my understanding it's because it's easier to check whether ints are between 1 and 4 than to check all the different casings and spellings people might use to input a string, so it's more bug-tolerant.
4) The getSuit() method returns the current value of the cardSuit instance variable, so a client of the class can store that information in a variable of their own.

Class to represent employees

Problem:

"Write the definition for a new class named Employee that stores the following data for a single employee:
 * The name of the employee (a String)
 * The name of the employee’s supervisor (also a String)
 * The employee’s annual salary (a double)

As with the other classes defined in this book, you should make sure that the instance variables containing these values are private and instead provide get and set methods to retrieve or change any of the values." (Roberts ch 6, problem 8)

/* File: Employee
 * ----------------------------
 * Class to store information about employees, retrieve that information, and reset the information.
 * How you'd use this class:
 * a) Enter in a new employee, ie " emp = new Employee('Bob Cratchit', 'Ebenezer Scrooge', 25.00) "
 * b) get information, ie " name = emp.getName() "
 * c) set information, ie " emp.setSupervisor('Mickey Mouse') "
 */

public class Employee {
    public Employee (String name, String supervisor, double salary) { 
        //LOCAL variables. Exist just for the run of this constructor method. The client passes name/suvervisor/salary information
        // in initially and it immediately gets used to set the instnace variable value.
        employeeName = name;
        supervisorName = supervisor;
        employeeSalary = salary;
    }
    
    //Getter methods:
    
    public String getName() { 
        return employeeName;
    }
    public String getSupervisor() {
        return supervisorName;
    }
    public double getSalary() {
        return employeeSalary;
    }
    
    //Setter methods: These have no return type, they just reset the instance variables
    
    public void setName(String newName) { 
        employeeName = newName;
    }
    
    public void setSupervisor(String newSupervisor) { 
        supervisorName = newSupervisor; 
    }
    
    public void setSalary(double newSalary) { 
        employeeSalary = newSalary;
    }
    
    // INSTANCE variables: Stuff that we're keeping track of for the lifetime of the object. 
    // It gets set using the temp (aka local) variables in the constructor
    
    private String employeeName;
    private String supervisorName;
    private double employeeSalary;

}

This chapter in the book gets students started with writing their own classes. The problem was very simple, but it's good refresher on how objects work see the difference between instance variables and local variables in action.

 It took me a while to get used to the fact that each piece of information is represented 3 times:
* In the constructor method, the client of this class creates a new instance of the "Employee" class and sets the initial name, supervisor and salary values. These are passed through as local variables that exist just for the life of the constructor method and instantly get stored to the instance variable.
* Instance variables that store the name, supervisor and salary values for the lifetime of the object.
* The getter method returns the name/supervisor/salary information from the current value of the instance variable, so clients of the class can store the information in a variable of their own. The setter methods update the instance variable based on new values that the client of the class passes (using a local value that exists just for the life of the setter method).

 Once I got a firm hold on why name/supervisor/salary information is distinct when represented in the local variables versus the instance variables, I got a better understanding of how classes work and how you'd write a class that other programs can use.

Friday, September 23, 2011

Arithmatic Tutor, updated with variable congrats messages

Problem: "To add variety to the interaction, modify your solution to exercise 5 so that it randomly chooses among four or five different messages when the student gets the right answer."

What it looks like:


The code was all the same except that instead of printing the hard-coded string "Right" if the user got the answer right, it printed answerAffirmation. This was a method that generated one of 4 random integers and mapped each integer to a different congrats message.

 if (userAnswer == programSolution) {
     println(answerAffirmation());
 }
 else {
     println("No, the correct answer is " + programSolution); 
 }

I used a switch statement. At first the method was buggy because the program thought I wasn't returning a result:

The problem was, even though having the strings map to one of four integers that I knew would be exhaustive, the program didn't realize that answers could only come from that random integer, so I must include a default string to get returned:

In reality the message "Grrrrreat!" won't get returned unless there's a bug with my method loops or with the rgen factory resource.


Sunday, September 18, 2011

Arithmetic Tutor Program (or, structuring and debugging loops)

Problem:

Write a program that poses a series of simple arithmetic problems for a student to answer.

Your program should meet these requirements:
• It should ask a series of five questions. As with any such limit, the number of questions should be coded as a named constant so that it can easily be changed.
• Each question should consist of a single addition or subtraction problem involving just two numbers, such as “What is 2 + 3?” or “What is 11 – 7?”. The type of problem—addition or subtraction—should be chosen randomly for each question.
• To make sure the problems are appropriate for students in the first or second grade, none of the numbers involved, including the answer, should be less than 0 or greater than 20. This restriction means that your program should never ask questions like “What is 11 + 13?” or “What is 4 – 7?” because the answers are outside the legal range. Within these constraints, your program should choose the numbers randomly.
• The program should give the student three chances to answer each question. If the student gives the correct answer, your program should indicate that fact in some properly congratulatory way and go on to the next question. If the student does not get the answer in three tries, the program should give the answer and go on to another problem.

(Roberts Ch 6, problem 7)

This was a fun problem to write, though debugging took a long time. Here was how I split up the problem, given the requirements. There are three major parts of this program:
1) Generate the arithmatic program.
2) Present it to the student and evaluate his answer
3) Stop the program after 5 presented problems.

These were my smaller steps:
* Generate two numbers (0-20) and an operator (comes from boolean true/false). Use random generator instance.
* Put them together and assess them so the program "knows" the correct answer
* If the result (“problemAnswer”) is not between 0-20, don't print anything and start again
* If it's between 0-20, then present the problem to the user. Declare "int userAnswer = readln(print the equation here)".
* To keep track of user attempts, start a local variable "countUserAttempts" and make it start at 1
* If problemAnswer == userAnswer, break from the loop (print that it's right) and start again
* If problemAnswer != userAnswer, then print it's wrong. Add +1 to the “countUserAttempts” variable and send them back thru the inner loop to try again.
* Let user submit a second answer. If it's right then print that it's correct and start again. If it's wrong then add +1 to the countUserAttempts variable (so now it’s three) and send them back thru.
* If it’s wrong again, then it will make countUserAttempts equal 4 so it will break from the inner “while” loop and roll down to the next argument and print the correct answer.

What it looks like:


/* File: ArithmaticTutor
 * This program shows a series of arithmetic problems to the user and evaluates his or her input.
 * In accordance with the problem specs, we only present components between 0 and 20, and make
 * sure that the answer (sum or difference) is between 0 and 20 as well before giving it to the user.
 * We make up a problem on the fly using 2 methods that each use a random generator instance;
 * one to generate the numbers to in our problem, and a second to decide whether the operator is plus 
 * or minus. There's also a method to collect the user's input. There are two count-keeping variables:
 * one, "countPresentedProblems," makes sure that we give the user only 5 problems (or 
 * however many are allowed by the "maxProblems" constant. The other, "countUserAttempts,"
 * which is inside the inner "while" loop, keeps track of user attempts to make sure 
 * he or she does only 3 attempts. If the user gets the answer right in 3 or fewer attempts, we print 
 * in 3 or fewer attempts, we print "Right!" and move on to the next problem. If not,
 * we just tell the right answer and move on.
 * 
 */
    import acm.program.*;
    import acm.util.RandomGenerator;

    public class ArithmaticTutor extends ConsoleProgram {
        public void run() {
            println("Welcome to Math Tutor! Prepare to be challenged.");
            int countPresentedProblems = 0; 
            while (countPresentedProblems < maxProblems) {
                // First we put together all the stuff needed for our problem and assess the first problem ourselves 
                int firstNumber = generateNumber(0,20); 
                int secondNumber = generateNumber(0,20); 
                boolean isPlusNotMinus = plusNotMinus();
                int programSolution = evaluateProblem(firstNumber, secondNumber, isPlusNotMinus);
                // Then we present it to the student (if the answer is between 0 and 20)
                if (programSolution > 0 && programSolution < 20){
                    countPresentedProblems +=1;
                    int userAnswer = getUserAnswer(firstNumber, secondNumber, isPlusNotMinus);
                    int countUserAttempts = 1;
                    while (countUserAttempts < 3 && userAnswer != programSolution) {
                        userAnswer = readInt ("Wrong. Try another answer:");
                        countUserAttempts += 1;
                    }
                    if (userAnswer == programSolution) {
                        println( "Right!");
                    }
                    else {
                        println("No, the correct answer is " + programSolution); 
                    }
                }
            }
         }
        private final static int maxProblems = 5;
  
        private RandomGenerator rgen = RandomGenerator.getInstance();
  
        private int generateNumber(int min, int max) {
            int number = rgen.nextInt(min, max);
            return number;
        }
        private boolean plusNotMinus() {
            return rgen.nextBoolean();
        }
        private int evaluateProblem (int firstNumber, int secondNumber, boolean plusNotMinus){
            if (plusNotMinus) {
                return firstNumber + secondNumber;
            }
            else {
                return firstNumber - secondNumber;
            }
        }
        private int getUserAnswer (int firstNumber, int secondNumber, boolean plusNotMinus){
            if (plusNotMinus) {
                return readInt("What is " + firstNumber + "+" + secondNumber + "?");
            }
            else {
                return readInt("What is " + firstNumber + "-" + secondNumber + "?");
            }
        } 
}
What made it hard: Keeping track of your loops. Poorly structured loops kept on causing bugs! For example there was a bug where if you entered 2 wrong answers in a row, it fell back to the “Wrong, the correct answer is [programAnswer]” part, even though it should wait till 3 wrong entries. The problem was that the part of the code that says “Wrong, the correct answer is [programAnswer]” was *inside* the "while" loop, so once we evaluated that it was wrong it would print the correct answer then still re-prompt for another attempt! Then I moved that “No, the correct answer is [correct answer]” part to outside the nearest loop, but then it started getting run for every submitted answer, even if they got it right! Here are my other bloopers, along with a brief explanations of what was wrong with the code when they appeared.

Sunday, August 7, 2011

Program to Flip a Coin (until you get 3 "heads" in a row):

"Write a program that simpulates flipping a coin repeatedly and continues until three consecutive heads are tossed. At that point your program should display the total number of times the coin was flipped." (Roberts ch 6, problem 2).

What it looks like:



/*
/* File: FlipThreeHeads.java
 * ----------------------------
 * This program simulates flipping coin repeatedly until you get 3 heads in a row, at which point you
 * print how many flips it took to get those 3. It uses an instance of the RandomGenerator class and keeps count using a local variable 'count.'
 */

import acm.program.*;
import acm.util.*;
public class FlipThreeHeads extends ConsoleProgram{
 
    public void run() {
     
        // Placeholders X, Y and Z to store the most recent flip and the past 2 flips (when they happen):
        String flipX = flipCoin(); 
        println(flipX);
        String flipY = null;
        String flipZ = null;
        
        // Local variable to keep track of how many flips we've done so far:
        int count = 1;
  
       //"As long as X, Y and Z aren't equal to each other and aren't 'heads'..."
        while ((flipX != flipY) || (flipX != flipZ) || (flipZ != "heads")){
            count += 1;
            String nextCoin = flipCoin();
            println(nextCoin);
            //Shove down the values of the placeholders to make flipX the most recent result  
            flipZ = flipY;
            flipY = flipX;
            flipX = nextCoin;
        }
        println("It took " + count + " tries to get 3 consecutive heads.");  
    }
 
    private RandomGenerator rgen = RandomGenerator.getInstance();

    private String flipCoin() {
        boolean booleanResult = rgen.nextBoolean();
  
        String flipResult;
        if (booleanResult == true) {
            flipResult =  "heads";
        } else {
            flipResult = "tails";
        }
        return flipResult;
    }
}

What made this hard/interesting:

Naming things is hard! Because this program requires that you keep track of the 3 most recent flips so that you can compare them and see if there were 3 heads in a row, you have to create a lot of variables. However, I kept being tempted to use variable names like "flipCoin" and "nextFlip" since they all do similar things related to the actual coin flip. If there's a way to make this program more spartan and not use as many variables that would be great.

Here's how a run of the program works and each step needs its own variable or set of variables:

1) You establish 3 local variables "flipX," "flipY" and "flipZ." As we keep flipping our programmatic coin these will keep track of the 3 latest flips. We will build a shove-over mechanism so that with each new coin flip, we'll turn flipX into the latest result, turn flipY into the old value for flipX, and turn flipZ into the old value for flipY.

Also, you create flipX with an initial value by calling the flipCoin() method.

2) The flipCoin() method is a private method that we call that just simulates flipping a coin. It works by pulling a random boolean out of our RandomGenerator instance and translating the returned "true" or "false" into "heads" or "tails."

3) booleanResult is a local variable inside the flipCoin() method that stores the "true" or "false" that gets returned from calling nextBoolean(). flipResult is a local variable that takes the boolean and stores the "head" or "tail" translation.

4) nextCoin is part of our main method and always stores the most recent flip. We keep resetting it as we keep on flipping coins (and resetting flipX to equal it and going on with the shove-down mechanism described in step (1).

The "flipCoin" method was particularly hard to make up names for inside because there are 3 variables that mean essentially the same thing (those that turned out to be called "flipResult," "booleanResult" and "flipCoin." I kept on being tempted to name them "flipResult", but all the distinct variables are necessary in order to return the desired result.

Sunday, July 31, 2011

Program to Draw a Random Card

Problem: Write a program that displays the name of a card randomly chosen from a complete deck of 52 cards. You program should display the complete name of the card. (Roberts ch 6, problem 1).

What it looks like (2 sample runs):

How the code looks:
/*
/*File: DrawCard.java
 * This program simulates drawing a card from a standard deck. It uses an instance of acm.util's 
 * RandomGenerator class to create two new random integers: one helping to supply the value (2-10, Ace, Jack, Queen, 
 * King), and the other integer helps determine the suit (Spades, Clubs, Hearts, Diamonds). Each integer value maps
 * to a card value or suit.
 *  * */
import acm.program.*;
import acm.util.*;

public class DrawCard extends ConsoleProgram{

    public void run() {
   
    int d1 = rgen.nextInt(1,4);
    int d2 = rgen.nextInt(1,12);
   
        String suit = null; //Declare a variable of null value. 
        //Then use switch statement to set a value
        switch (d1) {
            case 1: suit = "Spades"; break;
            case 2: suit = "Clubs"; break;
            case 3: suit = "Hearts"; break;
            case 4: suit = "Diamonds"; break;  
        }
   
        String value = null;
        switch (d2) { 
            case 1: value = "Ace"; break;
            case 11: value = "Jack"; break;
            case 12: value = "Queen"; break;
            case 13: value = "King"; break;
            default: value = Integer.toString(d2); break; // Returns a numeric value in string form
                // if a non-face card gets drawn
        }
        
    println("The " + value + " of " + suit);
   
    }
    //Instance variable for our random generator macheeeeen
    private RandomGenerator rgen = RandomGenerator.getInstance();
}

What made this interesting:

Two interesting concepts you exercise here:

1) Compartmentalizing your program. Instead of just storing 52 potential card values and randomly picking one of them, you can build something neater. There are 4 suits of equal distribution and 13 numeric values, so we can generate two random numbers for the face and numeric numbers and map them to card values. This is better than simply storing 52 potential card values because...

2) The concept of using an instance of a class to do stuff. In this case is a class of objects available to me called RandomGenerator. An instance of the RandomGenerator class is not one random number itself. It is an object that you can create in your program and then call upon to return random numbers. (It will recognize the method getInt() method). So the individual random numbers are a layer of abstraction away from the class that we get from the ACM library.

Why is this important?

This was actually familiar to me based on my work at Twilio. Twiio's REST API lets you make calls, send SMS messages, and pull information about your Twilio account. You can make a request to the API by a raw HTTP request to Twiio. Or, you can be clever and use a wrapper library that creates a "REST client". This is actually a class of objects that know how to make HTTP requests to Twilio, so instead of piecing together a big URL every time you need to communicate to Twilio, you can send commands to your instance of the REST client and communicate via methods instead of a raw URL.

Examples:

A1) Making a phone call directly via a direct HTTP POST to Twilio's API:

POST https://api.twilio.com/2010-04-01/Accounts/account123/Calls/
Auth Headers: username account123, password token456


POST parameters:
* To: 503-111-2222
* From: 503-222-3333
* Url: http://mycoolapp.renee.com


A2) Sending an SMS:


POST https://api.twilio.com/2010-04-01/Accounts/account123/SMS/Messages
Auth Headers: username account123, password token456


POST parameters:
* To: 503-111-2222
* From: 503-222-3333
* Body: Hello World

VERSUS

B) Making a phone call, then sending an SMS message using an instance of the TwilioClient class (from Sean Sullivan's Java wrapper library):

/*import twilio.client.*;
TwilioClient c = new TwilioClient("account123", "token456");

c.call("503-111-2222", "503-222-3333");
c.sendSMSMessage("503-111-2222", "503-222-3333", "Hello world");

See, isn't that better? The advantage is don't have to put together the URL every time or worry about validating each request. You just create your object, which has the account SID and auth token baked in and can recognize the methods "call" and "sendSMSMessage." Instead of needing to be familiar with the Twilio API (which is actually very simple), you can just be familiar with methods in your language of choice that let you make calls or send SMS.

Sunday, July 10, 2011

Program to Print Perfect Numbers

Problem: Greek mathematicians took special interest in numbers that are equal to the sum of their proper divisors (a proper divisor of n is any divisor less than n itself). They called such numbers *perfect numbers*. For example, 6 is a perfect number because it is the sum of 1, 2 and 3, which are numbers less than 6 that divide equally into 6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14.


Write a predicate method isPerfect(n) that returns *true* if the integer n is perfect, and *false* otherwise. Test your implementation by writing a main program that uses the isPerfect method to check for perfect numbers in the range 1 to 9999 by testing each number in turn. Whenever it identifies a perfect number, your program should display that number on your screen. Your program should find two other perfect numbers in that range as well. (Roberts ch 5, problem 12).


What it looks like:





/*
* File: printPerfects.java
* Name: Chu
* Section Leader: 
* This program prints the numbers between 1 and 9999 that are perfect numbers. Perfect numbers are those
* where the divisors (integers that divide evenly into it) all sum up to that number. It uses the private
* predicate method isPerfect.
* 
*/

 
package ch6_practice;
import acm.program.*;

public class printPerfects extends ConsoleProgram {
    public void run() {    
        for (int i = 1; i < 9999; i++) {
            if (isPerfect(i)) {
                println(i);
            }
        }
    }
    private boolean isPerfect (int n) {
        int sum = 0;
        for (int i = 1; i < n; i++) {
            if (n % i == 0) {
            sum += i; }
            }
            if (sum == n) {
                return true;
            }
        else return false;
        
    }
}

This was a simple little program that simply re-enforced the practice of breaking certain operations of a program into their own methods. The method "isPerfect" creates a new variable "sum", initialized at a value of zero. For any number that you're testing to see if it is perfect, you find all the divisors via brute force. Whenever you find a divisor, you add it to "sum." If, after finding all the divisors, the value of "sum" equals the number you're testing, then you know that the number is perfect.