Friday, September 20, 2013

Case Study: Rock, Paper, Scissors

I want to look at the following code before you begin building your own.  Copy the code below to a new Class (RockPaperScissors) and then "Auto Format" the code to see how that works.

This is a VERY different approach than what we've been doing so far.  They use a few codes we haven't seen before (i.e. boolean, String, while, nextLine, toLowerCase, ||, concat, etc.).  What are they doing?  What is "broken" in the code below?

Rock, Paper, Scissors:

import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
CPU cpu1 = new CPU();
Scanner sc1 = new Scanner(System.in);
boolean validmove = false;
String userMove = "";
while(!validmove){
System.out.println("Input your move (rock, paper or scissors): ");
userMove = sc1.nextLine();
userMove = userMove.toLowerCase();
if(userMove.equals("rock") || userMove.equals("paper")||userMove.equals("scissors")){
validmove = true;
}
}
String CPUMove = cpu1.getCPUMove();
cpu1.comparemoves(CPUMove, userMove);
}
}
class CPU{
public void comparemoves(String CPUMove, String userMove){
if(userMove.equals("rock")){
if(CPUMove.equals("rock")){
outputmoves("rock", "Tie!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "I win!");
}
if(CPUMove.equals("scissors")){
outputmoves("scissors", "You win!");
}
}
if(userMove.equals("paper")){
if(CPUMove.equals("rock")){
outputmoves("rock", "You win!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "Tie!");
}
if(CPUMove.equals("scissors")){
outputmoves("scissors", "I win!");
}
}
if(userMove.equals("scissors")){
if(CPUMove.equals("rock")){
outputmoves("rock", "I win!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "You win!");
}
if(CPUMove.equals("Scissors")){
outputmoves("scissors", "Tie!");
}
}
}
public void outputmoves(String cpuout, String status){
String output = "I played ".concat(cpuout).concat(".").concat(status);
System.out.println(output);
}
public String getCPUMove(){
int choice = (int) Math.floor(Math.random()*3);
String rpsmove = "";
switch(choice){
case 0: rpsmove = "rock"; break;
case 1: rpsmove = "paper"; break;
default: rpsmove = "scissors"; break;
}
return rpsmove;
}
}

Thursday, September 19, 2013

Case Study: Using Strings (Haiku)

Obviously I am out again today, so I am having to change it up a little bit.  Here's another program that I want you to play with.  This one uses strings and an interesting approach to formatting.  I commented some of the code to help you figure it out.

We're building a program that will generate Haiku poetry based on user input.  A haiku is a poem in 3 lines -- a line of 5 syllables, a line of 7 syllables, and a line of 5 syllables again.

Some examples of Haiku:
Falling to the ground,
I watch a leaf settle down
In a bed of brown.

It’s cold—and I wait
For someone to shelter me
And take me from here.
Snow falling slowly
Blanketing the trees and road
Silence and beauty.

Haiku Program:

//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

Wednesday, September 18, 2013

Looking at Code: Alphabet Formatting

Hi Guys!  So obviously I'm out sick today.  Instead of starting on the Rock, Paper, Scissors code today, I want you to do two things:

1.) Finish up your Fewest Coins Possible code
2.) Explore and experiment with the code below.  What is it doing?  How does it work?  Can you change it?

This is an interesting use of formatting and a "for loop" as well as the ++ option to count up. Let's look at how it works:

public class Alphabet
{
public static void main(String [] args)
{
    char current = 'A';
    for(int row = 1; row <= 3; row++)
    {
        for(int column = 1; column <= 10; column++)
        {
            System.out.print(current + " ");
            current++;
        }
    System.out.println();
}
}
}

Tuesday, September 17, 2013

Homework: Flow Chart & Begin Code for Rock, Paper, Scissors

Tomorrow we will begin coding a "Rock, Paper, Scissors" game. Create a flow chart demonstrating how a user will choose either rock, paper or scissors, and then the computer will make a choice.

If you aren't familiar with the game, two players will count to three and then throw out their hands with either a rock, a paper, or a scissor.

  • Rock beats Scissors
  • Scissors beats Paper
  • Paper beats Rock
You may want to think about counting points so you could play "best of 10" or even until someone enters "quit".

Monday, September 16, 2013

My Flow Chart: Minimum Coins Challenge

A question I had on Friday was, "Why would we ever need a program to tell us how many coins to give someone when we know how to easily count coins?"  It's a fair question and I will answer it after a brief description:

When I was a kid a cashier would ring up all of the items at the grocery store, people would pay the cashier (in cash), and the cashier would give currency (paper bills) to the customer.  While the cashier was counting the currency out, coins would automatically drop into a little tray in front of the customer.  Those coins were the minimum number of coins needed to avoid unnecessary trips to the bank for extra coins.  Today we don't use cash very often, so those little trays take up valuable counter space -- a space which today is typically filled with a credit/debit card reader.

However, most vending machines are still based on cash purchases [although many are slowly moving to credit/debit cards].  We typically associate vending machines with candy, snacks, and drinks.  We may put in $2.00 and buy a bottle of water for $1.25 and the machine kicks out three quarters in change.  We put in another dollar and buy a bag of chips for 80 cents and the machine kicks out 2 dimes.  You may be in a hospital waiting room and see a food machine that has sandwiches, burritos, etc.  You put in $2.00 for a $1.60 burrito and you get back a quarter, a dime and a nickel.  In some areas [amusement parks, for example] you can buy things like cameras, batteries, SD cards, t-shirts, and more.  That is all programming and [again] it's designed to kick back the minimum number of coins [or bills] for change.  When a particular coin is empty [i.e. there are no more quarters] the machine will stop accepting new money -- which means the owner of the machine will stop making money.  You COULD build in an algorithm that would say, "Uh oh... we're out of quarters.  Give two dimes and a nickel instead."  It's all up to the programmers.

Here's an example of a flow chart I made with a free online chart creator called "LucidChart".

I added process to remind me to import the Scanner (to get input) and to declare my variables.

Next I displayed (output) the Title and Instructions (asking for input in cents... 1 to 99).

Then I checked to make sure the input was in cents by less than one (i.e. .85) or greater than one dollar [100] (i.e. 154).

I added another check as an example to see if it was more than 1 but less than 2 (i.e. 1.54), although that won't happen because we will be declaring "amount" as an integer.

Next I calculate how many quarters are in the amount by dividing amount by 25.  I set the variable "quarters" to that number.

Then I figure out the remainder (the change left after quarters) by setting the new amount to amount - (quarters * 25).

I repeat these last two steps until I end up at pennies; at which time the left over amount will be less than 5 cents so whatever is left over will be in pennies.

Finally I display the coins.  Note that you COULD set up a routine that only displays a coin if there are coins in that category.  For example: "If quarters > 1 go ahead and display the quarter row."

I ended with a Stop, but we could easily have looped it back to the top to start over.

Work today to build this code, create a title graphic, and enhance your code in some way.  When you have finished, sign up for an account at Lucidchart.

Friday, September 13, 2013

Flow Chart & Code Homework

Here's another challenge that might be fun to try -- and will help keep you "code-limber".  :)

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.

Thursday, September 12, 2013

Some Interesting Video Clips