Saturday, October 20, 2012

This week we will be playing with some existing source code.  We will discuss what the programs do, how they are outlined, and what we can do to improve them.  Then we will attempt to expand on the programs.

CASE STUDY #1:  Movie Tickets


Let's look at this code for a movie ticket program:

import java.util.Scanner;
class TicketPrice {
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
int age;
double price = 0.00;
System.out.print("How old are you? ");
age = myScanner.nextInt();
if (age >= 12 && age < 65) {
price = 9.25;
}
if (age < 12 || age >= 65) {
price = 5.25;
}
System.out.print("Please pay $");
System.out.print(price);
System.out.print(". ");
System.out.println("Enjoy the show!");
}
}
 
  • First of all, what is the name of this Class?
  • What are we bringing into the Class from Java that is already built for us?
  • What does "Scanner" do?
  • What does "double" mean in Java?
  • What variables are we using in this code? (I see three)
  • What are some of the things that are missing in this code?
  • What would the ticket price be for an 8 year old?  A 14 year old?  A 66 year old?
  • Draw a flow chart indicating the flow of this program.
Next, let's update the source code:
  • Begin by formatting the source code to be more readable -- add line breaks, indent (Tab) some of the lines, etc.  (See the next case study for an idea of how to format it)
  • Add some comments to the code.  Remember that every Class needs a title, author(s), and version (number or dates) and maybe some comments describing what a formula or function does.

CASE STUDY #2: Divide Equally


Next let's look at this strange code for a program that will divide the total number of gumballs equally among a varied number of children:

import java.util.Scanner;

class EquallyDivide
{

    public static void main(String args[]) {
        Scanner myScanner = new Scanner(System.in);
        int gumballs;
        int kids;
        int gumballsPerKid;

        System.out.print("How many gumballs? ");

        gumballs = myScanner.nextInt();
        System.out.print("How many kids? ");

        kids = myScanner.nextInt();
        gumballsPerKid = gumballs / kids;

        System.out.print("Each kid gets ");
        System.out.print(gumballsPerKid);
        System.out.println(" gumballs.");
    }
}
 
So let's work with this code:
  • Add some comments / labels.
  • What is the difference between:
    •  System.out.println
    •  System.out.print
  • With variable names like "gumballs" or "kids" or "gumballsPerKid", this program is pretty specific.  What sorts of names could we use for variables to make this program usable for other purposes?  The "gumballs" variable might be more useful as "items", for example.  Remember, however, that you can change all instances of "gumballs" but "gumballsPerKid" is a completely different variable name.
  • Draw a flowchart indicating the flow of this program.
  • What code could we add to figure out how many gumballs are left over after they have been divided equally?
CASE STUDY #3:  Magic Cue Ball

For case number 3 we have "The Magic CueBall" -- okay, so it's ripped off... but it works... sort of:

import java.util.Scanner;
import java.util.Random;

class MagicCueBall {

    public static void main(String args[]) {
        Scanner myScanner = new Scanner(System.in);
        Random myRandom = new Random();
        int randomNumber;
        System.out.print("Type a Yes or No question: ");
        myScanner.nextLine();
        randomNumber = myRandom.nextInt(10) + 1;
        if (randomNumber > 5) {
            System.out.println("Yes. Isn’t it obvious?");
        } else {
            System.out.println("No, and don’t ask again.");
        }
    }
}
 
Let's do some playing with the code again:
  • Again, begin by adding comments/labels to the code.
  • What Java utils are we bringing in this time?
  • When you run this program, how does the output text differ from the text written in the code?
  • Before the "if" statement, randomNumber can be what possible numbers?  Why is there a +1 at the end of the line?
  • Add some variation to the possible responses:
    • 4 different "Yes" answers
    • 4 different "No" answers
    • 2 different "Ask Again" answers
  •  At the beginning of the program (before asking the user to type a yes or no question), add a title text graphic.  For example:
    • *********************************
    • * Magic Cue Ball 1.0 ~ by Your Name  *
    • *********************************
  •  What else could we add to make this application more usable?

CASE STUDY #4:  A Number Guessing Game -- Building a Program Step By Step





Step One: Let's try a different method for finding a random number -- this time from 1 to 1000.

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 999 + 1);
            System.out.println("Secret number is " + secretNumber); // to be removed later
      }
}
Step Two: Getting a Guess (import the Scanner and reply with the guess)
import java.util.Scanner;

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 999 + 1);
            System.out.println("Secret number is " + secretNumber); // to be removed
            // later
            Scanner keyboard = new Scanner(System.in);
            int guess;
            System.out.print("Enter a guess: ");
            guess = keyboard.nextInt();
            System.out.println("Your guess is " + guess);
      }
}
Step Three: Checking Your Answer
import java.util.Scanner;

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 999 + 1);
            System.out.println("Secret number is " + secretNumber); // to be removed
            // later
            Scanner keyboard = new Scanner(System.in);
            int guess;
            System.out.print("Enter a guess: ");
            guess = keyboard.nextInt();
            System.out.println("Your guess is " + guess);
            if (guess == secretNumber)
                  System.out.println("Your guess is correct. Congratulations!");
            else if (guess < secretNumber)
                  System.out
                             .println("Your guess is smaller than the secret number.");
            else if (guess > secretNumber)
                  System.out
                             .println("Your guess is greater than the secret number.");
      }
}
Step Five: Add Tries.
import java.util.Scanner;

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 999 + 1);
            System.out.println("Secret number is " + secretNumber); // to be removed
            // later
            Scanner keyboard = new Scanner(System.in);
            int guess;
            do {
                  System.out.print("Enter a guess: ");
                  guess = keyboard.nextInt();
                  System.out.println("Your guess is " + guess);
                  if (guess == secretNumber)
                        System.out.println("Your guess is correct. Congratulations!");
                  else if (guess < secretNumber)
                        System.out
                                   .println("Your guess is smaller than the secret number.");
                  else if (guess > secretNumber)
                        System.out
                                   .println("Your guess is greater than the secret number.");
            } while (guess != secretNumber);
      }
}
Step Six: Remove the Debug Script.
import java.util.Scanner;

public class NumberGuessingGame {
      public static void main(String[] args) {
            int secretNumber;
            secretNumber = (int) (Math.random() * 999 + 1);           
            Scanner keyboard = new Scanner(System.in);
            int guess;
            do {
                  System.out.print("Enter a guess (1-1000): ");
                  guess = keyboard.nextInt();
                  if (guess == secretNumber)
                        System.out.println("Your guess is correct. Congratulations!");
                  else if (guess < secretNumber)
                        System.out
                                   .println("Your guess is smaller than the secret number.");
                  else if (guess > secretNumber)
                        System.out
                                   .println("Your guess is greater than the secret number.");
            } while (guess != secretNumber);
      }
}
Step Seven: Suggestions for Continuing to Upgrade Your Code
  • Add comments and labels [obviously]
  • Create a little title text graphic to display at the beginning of your program.
  • Display "Guess #" in front of [or behind] each "Enter a guess" prompt.
  • Limit the number of guesses a user gets -- and you might even have it display something like "Guess 3 of 10".

No comments:

Post a Comment