Monday, October 29, 2012

Guess the Letter

// Guess the letter
class GuessLetter {
public static void main(String args[])
throws java.io.IOException {
char ch, answer = 'K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it: ");
ch = (char) System.in.read(); // get a char
if(ch == answer) System.out.println("** Right **");
else System.out.println("...Sorry, you're wrong.");
}
}

Boolean Numbers

// Demonstrate boolean values.
    class BoolDemo {
        public static void main(String args[]) {
            boolean b;
            b = false;
            System.out.println("b is " + b);
            b = true;
            System.out.println("b is " + b);
            // a boolean value can control the if statement
            if(b) System.out.println("This is executed.");
            b = false;
            if(b) System.out.println("This is not executed.");
            // outcome of a relational operator is a boolean value
            System.out.println("10 > 9 is " + (15 > 9));
    }
}

Characters

// Character variables can be handled like integers.
class CharArithDemo {
public static void main(String args[]) {
char ch;
ch = 'X';
System.out.println("ch contains " + ch);
ch++; // increment ch
System.out.println("ch is now " + ch);
ch = 90; // give ch the value Z
System.out.println("ch is now " + ch);
}
}

Working With Strings

Tonight we will be working with strings making a Haiku -- and, as usual, your homework will involve utilizing what you learn tonight.  :)

//Mad Libs Haiku

import java.util.Scanner;

public class Haiku
{
   public static void main( String[] args )
   {
   //create Scanner to get input from user
      Scanner input = new Scanner( System.in );

      String word1;//Person's name, 2 syllables
      String word2;//Noun, 2 syllables
      String word3;//Adjective, 1 syllable
      String word4;//Adjective, 1 syllables
      String word5;//Adjective, 2 syllables

      System.out.print( "Type a person's name -- two syllables: " );//prompt
      word1 = input.nextLine();//read user input

      System.out.print( "Type a two-syllable noun: " );//prompt
      word2 = input.nextLine();//read user input

      System.out.print( "Type a one-syllable adjective: " );//prompt
      word3 = input.nextLine();//read user input

      System.out.print( "Gimme another one-syllable adjective: " );//prompt
      word4 = input.nextLine();//read user input

      System.out.print( "Last one! A two-syllable adjective: " );//prompt
      word5 = input.nextLine();//read user input


      System.out.println( "\n\nHere is your Mad Libs-style haiku:\n\n" );
      System.out.printf( "I said to %s,\n", word1 );
      System.out.printf( "\"My love is like a %s:\n", word2 );
      System.out.printf( "%s, %s, and %s.\"\n", word3, word4, word5 );

   }//end method main
}//end class Haiku

Sunday, October 28, 2012

Bring your blue "Objects First with Java" books...

Bring your blue "Objects First with Java" books to class on Monday/Tuesday.  After we work through some more code examples and looking at the homework challenges, we're going to begin working on Chapter 3.

Friday, October 26, 2012

Homework Projects for Monday/Tuesday

I would like for you to create the following projects to bring in on Monday/Tuesday class:
  • Create a Class called CoinToss
  • Add appropriate comments, titles and attributions
  • Display a title "text graphic" when the program is executed
  • Ask the user to choose "heads or tails"
  • Generate a random number (using either of the methods that I showed you)
  • Display the going as a "text graphic" (either heads or tails)
  • Tell the user whether they win or lose
Create a simple menu program which allows users to run different routines:
  • Create a new Class
  • Add appropriate comments, titles and attributions
  • Display a title "text graphic" when the program is executed
  • Display a menu of at least 4 items
  • Have user input a menu choice (i.e. 1 - 4)
  • If the user did not enter a valid menu choice give them an error message and end program.
  • For each of the menu choices, do something different (i.e. one can generate a random horoscope, one can ask the user for two numbers to multiple, what can calculate the square feet in a room, etc.)
We will take some time to demo a few in class before we get started.

Fewest Coins Possible: The idea for this project is that we ask the user for the amount of change they have (let's assume it's $1 or less) and we figure out the fewest number of coins needed to total that amount. Now if you remember from the "Equally Divide" project we calculated a remainder as "Left Over" -- and this is similar to that. We will calculate the number of quarters needed, get the remainder, divide that by the number of dimes, etc.

♦ Set up variables for each coin type: Quarters, Dimes, Nickels, and Pennies
♦ Set up a variable for the currentCents
♦ Ask users to enter the amount of cents ($1 would be 100, for example)
♦ Calculate Quarters first, then find the remainder and set currentCents to the remainder amount
♦ Calculate Dimes from the remainder (again currentCents)
♦ Continue with Nickels and Pennies
♦ Display the results like, "Quarters: xx"
♦ Amounts to try: 91, 41, 59, 6 (and obviously others)

This program is definitely possible for you to complete knowing what you already know.

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



Tuesday, October 9, 2012

Course Textbooks

We have two textbooks for this Java Programming course:

  • Java Methods: Object-Oriented Programming and Data Structures (Second AP* Edition -- with GridWorld) by Maria Litvin and Gary Litvin.  [ISBN: 978-0-9824775-7-1]
  • Objects First With Java: A Practical Introduction Using BlueJ (5th Edition) by David J. Barnes & Michael Kölling.  [ISBN: 978-013-249266-9] 
  • Barron's AP Computer Science A test prep guide (5th Edition) [ISBN: 978-0-7641-4373-1]
We will also be connecting to various resources on the web.
  • One recommended text which you can view can be found here.