import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * A simple counter with graphical representation as an actor on screen. * * @author mik * @version 1.0 */ public class Counter extends Actor { private static final Color transparent = new Color(0,0,0,0); private GreenfootImage background; private int value; private int target; /** * Create a new counter, initialised to 0. */ public Counter() { background = getImage(); // get image from class value = 0; target = 0; updateImage(); } /** * Animate the display to count up (or down) to the current target value. */ public void act() { if (value < target) { value++; updateImage(); } else if (value > target) { value--; updateImage(); } } /** * Add a new score to the current counter value. */ public void add(int score) { target += score; } /** * Return the current counter value. */ public int getValue() { return value; } /** * Set a new counter value. */ public void setValue(int newValue) { target = newValue; value = newValue; updateImage(); } /** * Update the image on screen to show the current value. */ private void updateImage() { GreenfootImage image = new GreenfootImage(background); GreenfootImage text = new GreenfootImage("" + value, 22, Color.BLACK, transparent); image.drawImage(text, (image.getWidth()-text.getWidth())/2, (image.getHeight()-text.getHeight())/2); setImage(image); } }
Monday, December 17, 2012
Monday, December 10, 2012
Begin Greenfoot Game
Before we begin, check to see if Greenfoot is still installed on your station. If not, follow the previous instruction and install it. Then we will resume our basic game creation.
We will again be accessing the Joy of Code video tutorials for Greenfoot: http://blogs.kent.ac.uk/mik/category/joy-of-code/page/2/
Last week we used tutorial #4 to begin "Trick the Turtle". Basically we were able to add "instances" of the turtles to our "world" and have them behave as we programmed them to.
This week we will be continuing with the Trick the Turtle project using tutorial #5 (in Clearlake) and tutorial #6 (in both Clearlake and Lakeport). These two tutorials will add "If Statements" and "Random Behavior" to our game.
Time permitting we will also work through tutorial #7 to give the turtles some food, and then on to tutorial #8 to do some basic housekeeping and clean up our code.
Monday, November 26, 2012
Assignment: Teacher Contact
Assignment: Send me an email (rgriffith@kusd.lake.k12.ca.us) and answer the following questions:
- What would you need to see for you to call this Java Class "successful" at the end of the year?
- What would you like to get out of it?
- What are you willing to put into it?
Warm-Up: Getting Back to Java!
What I would like you to do as a warm-up activity is to comment, format and improve this game. Be creative:
import java.util.Scanner;
public class OOPExample1 {
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;
}
}
The New Boston video tutorials for Java
http://thenewboston.org/list.php?cat=31
Java
87 Videos
- 1 - Installing the JDK
- 2 - Running a Java Program
- 3 - Downloading Eclipse
- 4 - Hello YouTube
- 5 - Variables
- 6 - Getting User Input
- 7 - Building a Basic Calculator
- 8 - Math Operators
- 9 - Increment Operators
- 10 - If Statement
- 11 - Logical Operators
- 12 - Switch Statement
- 13 - While Loop
- 14 - Using Multiple Classes
- 15 - Use Methods with Parameters
- 16 - Many Methods and Instances
- 17 - Constructors
- 18 - Nested if Statements
- 19 - else if Statement
- 20 - Conditional Operators
- 21 - Simple Averaging Program
- 22 - for Loops
- 23 - Compound Interest Program
- 24 - do while Loops
- 25 - Math Class Methods
- 26 - Random Number Generator
- 27 - Introduction to Arrays
- 28 - Creating an Array Table
- 29 - Summing Elements of Arrays
- 30 - Array Elements as Counters
- 31 - Enhanced for Loop
- 32 - Arrays in Methods
- 33 - Multidimensional Arrays
- 34 - Table for Multi Arrays
- 35 - Variable Length Arguments
- 36 - Time Class
- 37 - Display Regular time
- 38 - Public, Private and this
- 39 - Multiple Constructors
- 40 - Set and Get Methods
- 41 - Building Objects for Constructors
- 42 - toString
- 43 - Composition
- 44 - Enumeration
- 45 - EnumSet range
- 46 - Static
- 47 - More on Static
- 48 - final
- 49 - Inheritance
- 50 - Graphical User Interface GUI
- 51 - GUI with JFrame
- 52 - Event Handling
- 53 - ActionListner
- 54 - Event Handler Program
- 55 - Intoduction to Polymorphism
- 56 - Polymorphic Arguements
- 57 - Overriding Rules
- 58 - Abstract and Concrete Classes
- 59 - Class to Hold Objects
- 60 - Array Holding Many Objects
- 61 - Simple Polymorphic Program
- 62 - JButton
- 63 - JButton Final Program
- 64 - JCheckBox
- 65 - The Final Check Box Program
- 66 - JRadioButton
- 67 - JRadioButton Final Program
- 68 - JComboBox
- 69 - Drop Down List Program
- 70 - JList
- 71 - JList Program
- 72 - Multiple Selection List
- 73 - Moving List Items Program
- 74 - Mouse Events
- 75 - MouseListener interface
- 76 - MouseMotionListener interface
- 77 - Adapter Classes
- 78 - File Class
- 79 - Creating Files
- 80 - Writing to Files
- 81 - Reading from Files
- 82 - Exception Handling
- 83 - FlowLayout
- 84 - Drawing Graphics
- 85 - JColorChooser
- 86 - Drawing More Stuff
- 87 - Series Finale
Monday, November 5, 2012
Beginning GridWorld
This week we will begin working through the GridWorld Case Study in the Java Methods book (pp.43-78). I have also created a packet (GridWorld AP Computer Science Case Study Student Manual) to use during this process.
To begin with, we'll need to download the source code (see previous post), unzip the file, and drag the GridWorldCode folder to the main Java folder. Then we'll add the GridWorld.jar file to the BlueJ library. Once that is complete we will be able to view and run the BugRunner program.
Read 3.1 Prologue: Consider how huge a computer program needs to be to do something like have a soldier run through a battlefield. Not only is the battlefield an object... and the soldier is an object... and the soldiers head is an object... and his eye is an object (if it has its' own properties)... but going deep enough, the pupil in the soldiers eye could be an object that dilates or contracts. As projects grow like this you will need to learn techniques to keep things organized.
Read 3.2 Case Study: GridWorld: The text describes the difference of class and objects again. And in the section where they describe the difference between the visual representation of objects and the coded objects themselves, you can think of programs like Minecraft where you can apply a different "skin" to an object. The program works exactly the same, but the skin is different. This is also the section where they have you read through Part 1 of the Student Manual (which I am providing you).
This section also discusses the important function of CRC cards for classes. In this example you can see two different classes (Predator and Habitat), the class "responsibilities" (generally what it does), and "collaborators" (other classes it depends on).
We will also be opening the BugRunner program and playing with the display.
To begin with, we'll need to download the source code (see previous post), unzip the file, and drag the GridWorldCode folder to the main Java folder. Then we'll add the GridWorld.jar file to the BlueJ library. Once that is complete we will be able to view and run the BugRunner program.
Read 3.1 Prologue: Consider how huge a computer program needs to be to do something like have a soldier run through a battlefield. Not only is the battlefield an object... and the soldier is an object... and the soldiers head is an object... and his eye is an object (if it has its' own properties)... but going deep enough, the pupil in the soldiers eye could be an object that dilates or contracts. As projects grow like this you will need to learn techniques to keep things organized.
Read 3.2 Case Study: GridWorld: The text describes the difference of class and objects again. And in the section where they describe the difference between the visual representation of objects and the coded objects themselves, you can think of programs like Minecraft where you can apply a different "skin" to an object. The program works exactly the same, but the skin is different. This is also the section where they have you read through Part 1 of the Student Manual (which I am providing you).
This section also discusses the important function of CRC cards for classes. In this example you can see two different classes (Predator and Habitat), the class "responsibilities" (generally what it does), and "collaborators" (other classes it depends on).
We will also be opening the BugRunner program and playing with the display.
Sunday, November 4, 2012
Bring Both Books This Week
Hey, folks. Let's go ahead and bring both Java books this week -- the BlueJ book and the big Methods book. We're going to explore some more of the clock program and begin looking at the Grid World project.
As we approach the GridWorld project we can find the necessary files at the CollegeBoard web site.
As we approach the GridWorld project we can find the necessary files at the CollegeBoard web site.
Thursday, November 1, 2012
Coin Toss Example
While this isn't the way we would probably have approached the coin toss project, this one is interesting because it tallies up the number of heads and tails we get out of 100 coin flips. This code involves using a counter, a Math.random number generator (0 or 1 is the result), a counter for the results of each of the sides of the coin, and a "do while" loop. Study the code and see if you can figure out what the unfamiliar code pieces are doing.
class Toss {
public final int HEADS = 0;
static int countH = 0;
static int countT = 0;
static int counter = 0;
private static int face;
public static void flip() {
face = (int) (Math.random() * 2);
}
public String toString() {
String faceName;
counter++;
if (face == HEADS) {
faceName = "Heads";
countH++;
} else {
faceName = "Tails";
countT++;
}
return faceName;
}
public static void main(String[] args) {
System.out.println("Outcomes:");
do {
flip();
System.out.println(new Toss().toString());
} while (counter < 100);
System.out.println("Number of Tails: " + countT);
System.out.println("Number of Heads: " + countH);
}
}
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:
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.
- 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 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.)
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:
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:
For case number 3 we have "The Magic CueBall" -- okay, so it's ripped off... but it works... sort of:
CASE STUDY #4: A Number Guessing Game -- Building a Program Step By Step
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.
- 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?
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]
- One recommended text which you can view can be found here.
Subscribe to:
Posts (Atom)