Java Graphics Cheat Sheet

Reviews
Shared by: armani11
Categories
Stats
views:
166
rating:
not rated
reviews:
0
posted:
11/9/2008
language:
English
pages:
0
The Book of Java Programming version 8.1 Table of Contents Beginning Java (J1 to J3) Print Formatting and Math Operations (J4 to J6) Button Basics (GUI 1to GUI6) Primitive Variables (J7 to J10) Input Programs (Input 1 to Input 6) If/Then Statements (IF1,IF2, Heart Rate, BMI, Tire) Looping (while loop & for loop programs) Multiple Choice Project Simple Drawings Random Numbers String Class Basics GUI with EasyApp Jeopardy Object Oriented Programming Applets Basic GUI Special Projects Review Programs HTML Basics Electronic Circuits Predator Prey on Isle Royale Mouse and Keyboard Input Example (Basic Quiz, Math Program) (OOP1 to OOP4) Cheat Sheets Java Cheat Sheet Graphics Cheat Sheet Java examples Simple graphics examples Table of Contents 1 Computer Science 1 – Java Assignments Beginning Java J1 Hello – Download and run the Hello Program. Brackets, syntax errors class Hello { public static void main ( String[] args ) { System.out.println("Hello World!"); } } J2 Worm – Download and run the Worm Program. class Worm { public static void main ( String[] args ) { System.out.println("A bird came down the walk:"); System.out.println("He did not know I saw;"); System.out.println("He bit an angle-worm in halves"); System.out.println("And ate the fellow, raw."); } } J3 Poem – Write a poem and add your name as a comment. Circle the matching braces when you print and turn in the program. //comment class Poem { public static void main ( String[] Argos ) { System(_______________________________); System.out.println(_______________________________); System.out.println(_______________________________); } } Table of Contents 2 Print Formatting and Math Operations J4 Write a program that prints your name and address on separate lines. Use the SimplePrint template on the class website. When you run the program the output should like the following: Your Name 1234 Montreal Avenue St. Paul, MN 55116 J5 Write a program that will display your class schedule. Use the SimplePrint template. Hint – use java cheat sheet (2 nd page) for Java Escape characters: System.out.println("Period \t Subject \tTeacher"); Your output should look like the following: Student Name: Bill Bagadonuts – Grade 11 Period Subject Teacher 1 Algebra II-Trig Lambert 2 English Hayes 3 Computer Science IB Moening 4 Physical Education Harnish J6 Write a program that will perform the following calculations (listed in green below). You could use the SimplePrint template. Include the problem and have the computer calculate the answer.: Hint – look at java cheat sheet (2nd page for Math Operations. System.out.println("10-3+5="+(10-3+5)); System.out.println("4+7^2 = "+(4+Math.pow(7.0,2.))); Your output should look like the following: 10-3+5=12 4+7^2=53 3*8+7=31 6^3=216 Table of Contents 3 Button Basics GUI1 Buttons: Download ( Edit – Add Class from File) and compile EasyApp and ButtonBasics. Look at ButtonBasics and get familiar with the program. Do the following: Change the name of ButtonBasics to GUI1 insert your name at the top of the program – also in two more places add a new row of buttons directly below the first row, name the buttons: Size Color Invisible in the actions block – copy and paste three if (source == buttonName) blocks for the Window Size Button – use the following code: setSize(800,400); for the Change Color Button – use the following code: setBackground(Color.red); for the Invisible Button – use the following code: bDoNothing.setVisible(false); GUI2 Buttons: Add another ButtonBasics class to your project ( Edit – Add Class from File and do the following: Change the name of the program to GUI2 – also in two more places insert your name at the top add two new rows of buttons (six new buttons), name the buttons: Red Blue Cyan Green Magenta Yellow Orange make each button change the color – use the code: setBackground(Color.red); GUI3 Labels: Add another ButtonBasics class to your project ( Edit – Add Class from File and do the following: Change the name of the program to GUI3 – also in two more places add the following under the buttons Label lNotes = addLabel("message here", 50, 100, 350, 50, this); Label lNote2 = addLabel("my Name is _______", 50, 250, 350, 50, this); add one more label in another location on the screen in the action block for bDoNothing – add the following code: lNotes.setText("hi"); Table of Contents 4 GUI4 Labels: Add another ButtonBasics class to your project ( Edit – Add Class from File and do the following: Change the name of the program to GUI4 – also in two more places add the following under the buttons Label lNotes = addLabel("message here", 50, 100, 350, 50, this); Label lNote2 = addLabel("my Name is _______", 50, 250, 350, 50, this); in the action block for bDoNothing – add the following code: lNotes.setText(“Scots!!"); in the constructor – add the following code: lNotes.setFont(new Font("Arial",1,24)); lNotes.setBackground(new Color(255,255,180)); lNotes.setForeground(Color.blue); add 4 more labels – change the font, font size, and color for all (the numbers for color must be between 0 and 255) Use the ColorMeter. GUI5 TextField: Add another ButtonBasics class to your project ( Edit – Add Class from File and do the following: Change the name of the program to GUI5 – also in two more places add the following under the buttons Label lNotes = addLabel("message here", 50, 100, 350, 50, this); Label lNote2 = addLabel("my Name is _______", 50, 250, 350, 50, this); TextField tUserName = addTextField("user name",50,200, 200,25,this); TextField tPassword = addTextField("password",50,225,200,25,this); add a Button to check password – use code below but change first two numbers Button bCheckPassword = addButton("Check Password",50,50,150,50,this) in the actions block – add the following: if (source == bCheckPassword) { if (tPassword.getText().equals("arrow")) lNotes.setText("You are logged on"); } GUI6 Make a GUI Make a program that uses Buttons, Labels, and Textfields. The program must do something. You must use at least 6 of the Buttons, Labels, or Textfields. You must use multiple colors. You must have more than one font type. Table of Contents 5 Primitive Variables J7 Integers – run the program. Experiment with the program. Try at least the following:  change 32 to 32.125 – what does the program do?  change 32 to 320000000000000000 (16 zeros) – what does the program do?  change 32 to 1000 – what does the program do?  how would you describe an integer? class Integers { public static void main ( String[] args ) { int value = 32; System.out.println("An integer: " + value); } } J8 Doubles – run the program. Experiment with the program. Try at the following:  change 32 to 32.5 – what does the program do?  change 32 to 32.125 (16 zeros) – what does the program do?  change 32 to 0.05 – what does the program do?  how would you describe a double? class DoubleCrash { public static void main ( String[] args ) { double value = 32; System.out.println("A double: “ + value ); } J9 Strings – run the StringTester Program.  Create another String variable called myName.  Set the value of myName to your name.  Print your name using the myName variable. class StringTester { public static void main ( String[] args ) { String words = "A" ; System.out.println("A String: " + words ); } } J10 Average Rain Fall: Using SimplePrint as a shell, write a program that averages the rainfall for three months, April, May, and June. Declare and initialize a variable to the rainfall for each month. For example: int April = 12; Compute the average, and write out the results, something like: Rainfall for April: 12 Rainfall for May : 14 Rainfall for June: 8 Average rainfall: 11.333333 Table of Contents 6 Input Programs Input1 Triangles, Rectangles, Circles Add the InputShell class to your project ( Edit – Add Class from File). Change the name of the program to AreaCalculator in all three places and do the following: Part 1: Rectangle Area  add a new button – name the button bRectangleArea (copy/paste bTriangleArea)  place the new button just to the right of bTriangleArea (change x coordinate only)  in the action block – make a new if block for the bRectangleArea button  Change bRectangle action block so that the program calculates the area of a rectangle Part 2: Circle Area (Area = PI * r * r)  add a new button – name the button bCircleArea (copy/paste bTriangleArea)  place the new button just to the right of bRectangleArea (change x coordinate only)  in the action block – make a new if block for the bCircleArea button  Change bCircle action block so that the program calculates the area of a circle Part 3: Advanced (for A Level Work) o add a button to calculate the area of a trapezoid o add buttons to calculate the perimeters of triangles, rectangles, circles, and trapezoids Input2 Skid Marks: write a program that will determines a car’s speed based on the skid mark the State Highway Patrol measures at an accident scene. Add the InputShell class to your project ( Edit – Add Class from File). Change the name of the program to SkidMarks in all three places and do the following:       change the bTriangleArea button to a “Determine Speed” – name the button bSpeed create two variables (both doubles) speed and distance in the action block – modify the TriangleArea block for bSpeed input one integer for distance – see code below o distance = inputDouble("Enter the length of the skid mark"); calculate speed in MPH of the car Speed = Math.pow(30*distance*.7, 0.5); output the velocity of car (use one output box) The skid distance was 100 feet, the vehicle was traveling 45.8257569 miles per hour. Table of Contents 7 Advanced Programmers – if the speed is greater than 55MPH – remind the police officer to write a speeding ticket. Input3 Cat Launch: write a program that will determine the maximum height and time of flight for a Cat (assuming it is shot straight up while ignoring air resistence and PETA). Add the InputShell class to your project ( Edit – Add Class from File). Change the name of the program to CatLaunch in all three places and do the following:    change the bTriangleArea button to a “Cat Launch” – name the button bCatLaunch create three variables (all doubles) velocity, height, time in the action block – modify the TriangleArea block for the cat launch o input one integer (the cat velocity in feet per second) – see code below velocity = inputDouble("Enter the cat’s initial velocity in feet per second"); o calculate height and height for the cat in the action block – see formulas below Height = (Velocity*Velocity)/(64.4); Time = (2*V)/32.2; o output the height and velocity for the cat (use one output box). Your output will look like the following for 500 feet per second: Cat’s Initial Velocity = 500 feet per second Maximum Height = 3,881 feet Time of Flight = 31 seconds YOUR FINAL GRADE DEPENDS ON YOU DETERMINING THE INITIAL VELOCITY REQUIRED TO PUT A CAT AT 10,000 FEET. Input4 GPA Calculator. This program will calculate your Grade Point Average (GPA). Add the InputShell2 class to your project ( Edit – Add Class from File). Change the name of the program to GPA in all three places and do the following: o add three more textfield for periods 4, 5, and 6 o create three more variables for P4, P5, P6 o in the constructor, put your name in the title, change the color and the font Table of Contents 8 o fix the action block for Periods 4, 5, and 6 Table of Contents 9 Input5 Cents to Dollars Write a program that reads in a number of cents. The program will write out the number of dollars and cents, like this: The program should give results like the following: Input the cents: 324 That is 3 dollars and 24 cents. For this program you will use integer arithmetic and will need to avoid using doubles. Review your notes on the integer remainder operator %. Use Money as a shell. Input6 Correct Change Write a program that reads change due to a user (in cents) and writes out how many dollars, quarters, dimes, nickels, and pennies she is due. When cashiers in a store give you change they try first try to "fit" dollars into the amount you get back, then try to "fit" quarters into what is left over, they try to "fit" dimes into what is now left over, then try to "fit" nickels into what is left, and finally are left with a few odd cents. For example, if change is 163 cents: * One dollar fits into 163, leaving 63 cents. * Two quarters fit into 63 cents, leaving 13 cents. * One dime fits into 13 cents, leaving 3 cents. * No nickels are needed. * Three cents are left. Your change is : 1 dollar, two quarters, one dime, and three cents. Use Money as a shell. Table of Contents 10 If/Then Statements IF1 Copy and run program IF1.  Change the program – make the value of y bigger than x.  Add another print statement to the multiple line if statement  Add a third if statement that checks if x == y and prints a message public class if1 { public static void main (String [] args) { int x = 1000; int y = 10000; //single line if statement if (x>y) System.out.println(x + " is bigger then " + y); //multiple line if statement if (y>x) { System.out.println(y + " is larger then " + x); System.out.println("goodbye"); } } } IF2 Copy and run program IF2.  Change IF2 – add an if statement so it only prints numbers from 100 to 50.  Add an if statement so that all numbers from 49 to 1 get printed twice.  Finally – only print odd numbers from 100 to 50 public class If2 { public static void main (String [] args) { int x = 100; while (x>0) { System.out.println(x + " "); x = x-1; } } } Table of Contents 11 IF3 Maximum Heart Rate Use the MaxHeartRate Program to asks a user for their age, gender and level of fitness. Then have the program calculate the person’s Maximum Heart Rate using the formulas below. Male Non-Athletic Male Athletic Female Non-Athletic Female Athletic Max Heart Rate = 220 -Age Max Heart Rate = 205-Age/2 Max Heart Rate = 226-Age Max Heart Rate = 211-Age/2 import java.io.*; public class MaxHeartRate { public static void main() throws IOException { EasyReader console=new EasyReader(); int age; char gender; String fit; int maxHeartRate=220; System.out.println("Enter your age"); age = console.readInt(); System.out.println("Enter M or F for gender"); gender = console.readChar(); System.out.println("Are you physically fit? Enter yes or no"); fit = console.readLine(); if (gender =='M' && fit.equals("yes")) { maxHeartRate = 205-age/2; } //here you add three more if statements System.out.println("Your Maximum Heart Rate is " + maxHeartRate); } } Table of Contents 12 IF4 Body Mass Index BMI Edit the BMICalculator and EasyReader program to ask the user for their weight and height. Then have the program figure out the person’s BMI number. Use if else statements to determine the user’s weight status. The output would look like the following: Your Height is 68 inches and your weight is 125. Your BMI is 18.5 and your weight status is normal. Body Mass Index is a tool for indicating weight status in adults. To determine a persons BMI, use the following formula BMI = ( Weight in Pounds / ( Height in inches ) x ( Height in inches ) ) x 703 BMI Below 18.5 18.5 – 24.9 25.0 – 29.9 30.0 and Above Weight Status Underweight Normal Overweight Obese *As BMI increases, the risk for some disease increases. Some common conditions related to overweight and obesity include: Cardiovascular disease, High blood pressure, Osteoarthritis, Diabetes. IF5 Tire Pressure The front tires of a car should both have the same pressure. Also, the rear tires of a car should both have the same pressure (but not neccessarily the same pressure as the front tires.) Write a program that reads in the pressure of the four tires and writes a message that says if the inflation is OK or not. Input right front pressure 38 Input left front pressure 38 Input right rear pressure 42 Input left rear pressure 42 Inflation is OK Table of Contents 13 IF5 Part 2 More Tire Pressure (B level) Its not enough that the pressures are the same in the tires, but the pressures must also be within range. Modify the program so that it also checks that each tire has a pressure between 35 and 45. If a tire is out of range, write out an error message immediately, but continue inputting values and processing them: Input right front pressure 32 Warning: pressure is out of range Input left front pressure 32 Warning: pressure is out of range Input right rear pressure 42 Input left rear pressure 42 Inflation is BAD If there have been any warnings, write out a final error message. (To do this, declare a boolean variable goodPressure that is initialized to true but is changed to false when an out of range tire is first found.) IF5 Part 3 The Pressure is Building (A level) Tires don't have to have exactly the same pressure. Modify the program for exercise 2 so that the front tires can be within 3 psi of each other, and the rear tires can be within 3 psi of each other. Input right front pressure 35 Input left front pressure 37 Input right rear pressure 41 Input left rear pressure 44 Inflation is OK Table of Contents 14 while loop Programs while1: Write a program that uses a while loop to print out your name 1,000 times. while2: Write a program that uses a while loop to print out the numbers from 1 to 500. while3: Write a program will print even numbers from 2 to 100, 2,4,6,8…….. while4: Word Repeater (looping with input) Write a program that asks the user to enter a word. The program will then repeat word for as many times as it has characters: Enter a word: Hello Hello Hello Hello Hello Hello Hello gets repeated 5 times because it has five letters. You need to use the length() method that counts the number of characters in a string: String inputString; int times; times = inputString.length() while5 Adding up Integers Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum. How many integers will be added: 3 Enter an integer: 3 Enter an integer: 4 Enter an integer: -4 The sum is 3 You will have to put your 2nd input statement inside of a while loop. Table of Contents 15 for loop Programs for1: Write a program to print the numbers from 2 to 60, going up by an increment of 2. Use the for loop shell on the web page. for2 Write a program that uses FOR Loop to print out numbers from 5 to 35 for3 Write a program that uses a FOR Loop to print out the numbers from 30 to 1 for4 Write a program will print multiples of 3, from 30 to 3000 close together, 3,6,9,12…….. for5 Write a program that will use one for loop and o ne print st ate ment to produce this graphic (make sure it is centered) &&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&& for6 Write a program that uses one for for loop and three (only three) print statements to produce ########## ## ## ## ########## A Level for7 Write a program that only has one print command in a FOR loop to provide the following output. You may use another PRINT command outside the FOR/NEXT loop. The letter “Y” can be used only one time in your program. Y YY YYY YYYY YYYYY YYYYYY Write a program that only has TWO print commands in FOR/NEXT loops to provide the following output. You may use another print command outside the FOR/NEXT loops. The letter “Y” can be used only one time in your program. Y YY YYY YYYY YYYYY Y YY YYY YYYY YYYYY Y YY YYY YYYY YYYYY A Level for8 Advanced: Table of Contents 16 Multiple Choice Project Pick a topic and write a quiz program that contains ten questions about the topic. Topic ideas – computer science, biology, history, geography, trivia, sports, entertainment, dating matching. The user should see:  Introduction (introduce your topic – tell user how they will be graded)  Ten Questions about your topic with multiple choice answers  Ending – tell the user how they did – give them a score A very simple template is provided on the webpage. Extra Credit – win one of the following categories  most educational  most entertaining  most creative Optional Ideas  put the quiz on an applet  add color and graphics  add GUI Table of Contents 17 Simple Drawings D1 Stickman Applet: Using the HappyFace.java program create a stickman with the following features;  body – arms and legs  use three different colors and a background color  use two Strings  look at bouncingRect.java and get it to move D2 Pictures - draw at least two of the following pictures on graph paper, and then use plot statements to draw the following shapes. Store each shape as individual files. Fruit Space Ship Tank Skier Spear Airplane Parachute Your Choice D3 Backdrop - Create a backdrop/landscape for your computer game. Draw one of the following pictures on graph paper, and then use plot statements to draw on the screen. Urban Desert Outerspace Moon Tropical Island Your Choice. D4 Animation. Add animation to one of your graphics from #1. Grading Criteria for D2, D3, and D4 (20 points total) Your Score 0 to 5 5 to 10 10 to 15 15 to 17 landscape. 18 to 20 You have drawn something – it may not be recognizable You have drawn two pictures and a backdrop or landscape. You have added an audio clip to your two pictures or landscape You have added an audio clip and imported a picture to your You have animation in addition to everything else above. Table of Contents 18 Random Number Programs R1 R2 R3 Write a program that prints 100 random numbers from 5 to 10 (e.g. 5 7 9 6 5 8..) Write a program that prints 7,000 random numbers from 1 to 2 (e.g. 1 1 2 1 2 …) Write a program that prints 500 random numbers from -30 to 10 R4 Write a program that simulates the throwing of one die (dice) with six sides. Have the program roll the die 40 times and will print the results. (1 4 6 2 4) R5 Write a program that simulates the throwing of two dice 20 times. The program should count the number of times two ones are rolled and should count the number of times a total of six is rolled. The output should look like the following (but with random numbers): hint - the INT/RND statment from program B36 will be used twice in this program 1st Die 2 6 2nd Die 4 3 Total 6 9 A Level R6 Write a program to help a student learn basic multiplication facts. Imagine that you wanted to use the computer as an electronic flash card device. Give the student ten multiplication problems with numbers from 1 to 9. Tell the student if their answer is correct or incorrect. When complete, the user will be told how many correct they have. If nine or more are correct, the user will be congratulated. If less than 9 correct, the user will be encouraged to try again Table of Contents 19 String Class Basics 1. Declaring and setting String Variables String message = “Hello”; 2. Concatenation of Strings Sentence = message + “my friends”; 3. Classes – structure that makes Objects (cookie cutter) Objects – store data can take action Methods – actions an object may take example: int n = message.length(); sometimes put info in here called parameters object of String Class 4. Commonly used String Methods .length() .equals(anotherString) .toLowerCase(someString); .charAt(position) String Method 5. Write a program that accomplishes the following (use the API for String Class Information): have a user input a String write print statements that output the length of the String the original String in Upper Case the character in the 2nd slot removes all spaces that the user entered between words checks to see if the String ends with “ed” returns the index of the first occurrence of the letter “c” replace all “a” letters with “b” letters check to see if the String starts with a “b” Table of Contents 20 GUI with EasyApp Basic Quiz Download the BasicQuiz program, compile and test it - you will need EasyApp.  Add three new buttons to the quiz to ask a question you find interesting.  add an exit button that functions (Math Program provides an example)  make at three improvements to the program – document with comments Math Program Use the GUIMath and EasyApp program on the webpage a. Use textfields for for input and output, and buttons for actions like calculating an answer. Have the GUIMath program complete the following:    Cube – accept a number and calculate the cube of the number (this part has been done as an example) Absolute Value – accept a number and calculate the absolute value of the number (hint: use Math.abs(x)) Square Root – accept a number as input and calculate the square root of the number (hint: use either the Math.sqr(x) or Math.pow(x,0.5) Cube roots - accept a number as input and calculate the cuberoot (hint - use Math.pow(x , 0.333333333333) Adding – accepts two numbers and adds them Money Conversion another country. convert US dollars to a currency from     Quadratic Formula - input A,B,C for a quadratic equation, and calculate the two roots, using the quadratic formula (if you don’t know the quadratic formula – look it up). Table of Contents 21 Jeopardy The program is a simple version of the game Jeopardy, where the user answers questions and wins money for correct answers and loses money for incorrect answers. After each question, the button is disabled, so that question cannot be chosen again.  Add buttons for at least 3 questions in each category (100, 200, 300). Make sure each button is disabled after use, and that it adds or subtracts the correct amount. Improve the ANSWER algorithm(s): o Change IF commands so they take both CAPITAL and small letters. o Add a HINT for each question by telling:  the FIRST LETTER of the answer  the number of letters in the answer o Use a STRING command sensitive to make the scoring NON-case-  o Use a STRING command to accept an answer as long as the first 3 letters and the last letter are correct thus, it would ignore some spelling mistakes. o Allow the person to guess again if their answer is PART OF (contained in) the correct answer.  Change the game to be played by 2 players. o This means there must be a variable to keep track of which player is answering, and that must switch automatically between the two players after each question. o There must also be 2 variables for scores (scoreA and scoreB), as well as two TextField boxes for displaying the scores. o change the program so that if a player gets a question correct, they get another turn. They should keep playing until they give an incorrect answer. o Add a "Daily Double" question, where the player can "bet" as much money as they wish, up to the amount they currently have.  Choose random questions from a group of 10 questions in each category. Do this the easy way, and don't try to stop repeat 22 Table of Contents questions - e.g. the same question might be asked twice if the player is lucky. Table of Contents 23 Beginning Object Oriented Programming Program OOP1 1. Download, compile and run Class Student and StudentTester 2. In Student, create a method called setGrade – it will receive a student’s grade (freshman, sophomore, junior, senior). public void setGrade(String gd) { grade = gd; } 3. In Student, create a method called getGrade – it will return the student’s grade. public String getGrade() { return Grade; } 4. In StudentTester – insert these lines of code one.setGrade("Senior"); String g = one.getGrade(); System.out.println("Grade: " + g); Program OOP2 1. Download, compile and run Class Customer and CustomerTester 2. In class Customer, create methods to set last name, middle initial , savings, and cash. Use Strings, Characters and Integers where appropriate. 3. Add a method to return total money (savings+cash) and one to return the whole name. 4. In class CustomerTester, use the object one as a reference to call and set the last name, middle initial, savings, and cash. 5. Declare a String that will get the whole name from class Customer. Use one to reference the method. 6. Declare an int that will get the total money from class Customer. Use one to reference the method. 7. Use a println to output the name and money. 8. A Level – prior to printing, use the Date Class to print out current date and time. 9. A Level – Use JoptionPane to input the persons name and data instead of hard coding this information in the CustomerTester. Table of Contents 24 Program OOP3 1. Download, compile and run Class CarCustomer and CarCustomerTester 2. In class CarCustomer, use the constructor to add last name, middle initial, savings, and cash. Also declare these variables. 3. In class CarCustomer, add a method to return total money (savings + cash). 4. In class CarCustomer, add another method to return the whole name. 5. In class CarCustomerTester, add Smith, B, 1000, and 500 to the call to the constructor of object one. 6. In class CarCustomerTester, declare a String that will get the whole name from class CarCustomer. Use one to reference the method. 7. in class CarCustomerTester, declare an int that will get the total money from class CarCustomer. Use one to reference the method. 8. In class CarCustomerTester, output the name and money. 9. In class CarCustomerTester, create another object called two and use your name and parameters. The class Customer does not get changed. Program OOP4 – Simple Aquarium 1. Fully comment the program – every line that has // must be commented 2. Add two more: - fish types - fish colors 3. 4. 5. 6. Count up and print out the number of each fish type. Calculate and print the average age of the fish Before printing, sort the fish by type and then by age. Create a GUI Aquarium Table of Contents 25 Applets Applet 1 Drawing Stuff: The DrawingStuff applet provides examples of different shapes you can draw. Change the program to accomplish the following:  add a new fillRectangle (top right corner)  add a new fillOval (bottom right corner)  add a fillArc (bootm left corner)  add a drawString (ltop left corner with your name as the String)  use the drawString command to make a Triangle Each of the above shapes should be a different color. Applet 2 Moving Rectangle: The bouncingRect applet makes a box that moves across the screen. Change the program to accomplish the following:  change the this color of the shape  give the box a smilely face  have the box start again from x=0 after it passes x=400  make the box bounce back and forth off the walls Advanced - have the box move up and down Advanced - make the box bounce off the walls like a pool shot Applet 3 Launch a Rocket Use the tools you learned Applet 1 to draw a simple rocket. Then use Applet 2 to launch the rocket. Place a countdown on the screen and then have the rocket shoot from the bottom of the screen to the top of the screen. If you can, make the rocket spew smoke or flames. Applet 4 – Screen Saver: Write a program that acts like a screen saver. The program must use at least two of the following geometric concepts (shift,scale, or rotate), use multiple colors. Table of Contents 26 Applet 5: Download and run the Fireball program. Change the program to accomplish the following:  get the fireball to move faster  have the user enter the fireball velocity and angle measure  put a target on the screen  give the user ten tosses  tell the user if they hit or miss the target - keep score  have the firebal kick updust when it hits the ground  put a landscape in the background  put a wall in front of the target to shoot over (can’t shoot through it)  have user depress the space bar multiple times to increase the velocity of fireball  have the user see the target in a different location for each throw  have a bird fly around the screen - what happens if you hit it?  what else can you figure out to do? 1 Games – you pick one to make Game 1 Target Shooting make a box move on the screen. do not allow the box to leave the screen make the box jump have a projectile leave the box if the projectile hits a target - score a point make the target move have the target launch projectile at the box add your own features Game 3 Yatzee - create a Yatzee game. Game 4 Slot Machine - create a slot machine game. Have user INPUT money and then deduct money after each pull of the slot machine. Determine how to award money to the user - i.e. two matching numbers may be a partial payout - three matching numbers is the jackpot. As a casino operator you have to ensure the casino is making money - and the user is entertained. Game 5 Spear Toss - see the real thing - incorporate as many features as you can. Game 6 Worm - see the real thing - incorporate as many features as your can. Game 7 - create a program that allows a user to paint on the screen. Appleworks Paint Program for ideas. See the Game 8 Simon - create a program that duplicates the SIMON game. Determine how many random numbers a person can repeat in a row. Game 9 Pong - create a one person or two person PONG game. Table of Contents 27 Table of Contents 28 Basic GUI 1. Open a new project in Bluejay and label it yourName GUI 2. Download the GUI Main and Framer file from the class webpage. 3. Replace the f.setSize line of the Main with f.setBounds(0, 0, 300, 200);. The first argument determines the x position on the screen. The second argument determines the y position on the screen. The last two arguments determine the width and the height. 3. Change the color of the frame to something other than red. 4. Try using different heights and widths in the Main. 5. Colors: Download the Colors file. Add 10 new colors to the Colors class. 6. In Framer – replace the original setBackGround with the following: setBackground(Colors.purple); We can access the object, purple, using the name of the class, Colors, as a reference because the object purple is static. 7. Labels: Change the code of Framer to the following (Label is a class in java.awt.*.): import java.awt.*; public class Framer extends Frame { Label mess1 = new Label("Hello"); public Framer() { setLayout(null); setBackground(Color.blue); add(mess1); mess1.setForeground(Color.red); mess1.setBackground(Color.green); mess1.setBounds(50, 50, 100, 30); } } Table of Contents 29 8. Fonts Download the Fonts file. Create two other fonts within the Fonts Class. Then, use the Fonts class in Framer as follows: import java.awt.*; public class Framer extends Frame { Label mess1 = new Label("Hello"); public Framer() { setLayout(null); setBackground(Color.yellow); add(mess1); mess1.setBounds(50, 50, 100, 30); mess1.setFont(Fonts.bigFont); } } 9. Advanced Labels. Using the graphics design sheet, place 6 labels on the grid. Add messages to the labels. Label the coordinates and width and height for each label. When the graphics design sheet is finished, go to your computer and add the labels to Framer.  use all the different fonts that you have created.  add a background color to the frame as well as the labels  set the color of the text of each label. This project will be graded on its overall appearance together with the design sheet. Turn in the design sheet when you show me the final output of the project. 10. Buttons. Download the Buttons class. In the Main program change the driver to Buttons F = new Buttons(); Once you get the program running, add two more buttons to the project. Table of Contents 30 11. More Buttons. Download the Action Class. In the Main program change the driver to Action f = new Action(); In order to add action to a Button, you add to do 4 things to the code: Step 1: import java.awt.event.*; Step 2: implements ActionListener Step 3: addActionListener(this); Step 4: public void actionPerformed(ActionEvent e) { } In the actionPerformed method, the line, if(e.getSource() == b1), is not necessary since there is only object, b1, which has the ActionListener added to it. If you omit this line the program will run the same. However, I recommend using it to avoid problems in the future. The line, mess1.setText("Good Bye");, places a String in the Label, mess1. The command only works with Strings. Try adding several more buttons that will change the text on the label. Add one button that will leave the label blank. 12. And More Buttons. Download the MoreAction Class. change the driver to MoreAction f = new MoreAction(); In the Main program In this program, we want 4 things to happen when the Button is clicked. Those 4 things are placed between curly brackets after the if statement. Assignment Declare a method, public void message1(), before the final closing bracket. Cut the 4 lines of code following the if statement and paste them into message1. Put in a call to message1 where the code was taken out. Try adding several more buttons that will change the text and appearance of the frame and label. Each Button click should call a different method. Table of Contents 31 First GUI Shell J5 Download and run the AddTwo Applet. Change the program so the program not only does addition, but also does subtraction, multiplication, and division (each on a different label). J6 Modify J5 so the applet would with decimal numbers – you should use “doubles”. J7 Make an Applet that converts one quantity to another (like miles to feet or pounds to kilograms). Use Labels to indicate what you expect the user to type into the TextFields. Table of Contents 32 Computer Science 1 – Special Projects 1. Phone Book (find shell at Kjell Chapter 54) - add a record. First Name, Last Name, Phone Number - print the phone book to the screen - sort records by Last Name - sort records by phone number - write to a file using object serialization - delete a record - search for a record using last name (return all names and print to screen) - search for a record using first and last name (return single match and print to screen) 2. Phone Book - add a GUI interface 3. Write a program with a GUI interface to help a student learn basic multiplication, division, adding and subtracting. - Give the student ten problems (one at a time) with numbers from 0 to 10. - Tell the student if their answer is correct or incorrect. - When complete, the user will be told how many correct they have. - If nine or more are correct, the user will be congratulated. - If less than 9 correct, the user will be encouraged to try again - add a noise for correct and incorrect answers - have student log in with name - keep track of student’s scores 4. Create a program that demonstrates importing and exporting a MS Excel file. 5. Create a GUI Aquarium. Each fish object should be shown on the screen. Add a category for fish size. Use fish images that you find. 6. Create a Blackjack Game with a GUI interface. Get shell classes from IB CS website. CS1 Students registered for class with previous programming experience - A Level: Complete 5 of the six programs - B Level: Complete 4 of the six programs Table of Contents 33 Review Programs Input Review: Write a program that asks the user how many Fibonacci numbers they would like to have printed on the screen and then determine the Golden Ratio. Output may look like: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025… The ratio of the last two numbers is 1.6180 Use TriangleReaderTester and EasyReader as shells. If Statement Review: In a new role-playing fantasy game players must design their character by picking a point value for each of three characteristics: * Strength, from 1 to 10 * Health, from 1 to 10 * Luck, from 1 to 10 Write a program that asks for a name for the character and asks for the point value of for each of the three characteristics. However, the total points must be less than 15. If the total exceeds 15, then 5 points are assigned to each characteristic Welcome to Yertle's Quest Enter the name of your character: Chortle Enter strength (1-10): 8 Enter health (1-10): 4 Enter luck (1-10): 6 You have give your character too many points! Default values have been assigned: Chortle, strength: 5, health: 5, luck: 5 Table of Contents 34 While Loop Review Write a program that adds up the squares and adds up the cubes of integers from 1 to N, where N is entered by the user: Upper Limit: 5 The sum of Squares is 55 The sum of Cubes is 225 Do this by using just one loop that generates the integers. For Next Statement Review Write a program that writes a tree made of stars on the terminal. You can only use two print statements in your program. * *** ***** ******* ********* *********** ************* *************** *** *** *** “A” Level Review Programs 1. Write a program that lists all the prime numbers from 1 to 1,000,000 2. Write a program to check if a number that is inputed from the keyboard is prime. Table of Contents 35 HTML Projects HTML Project 1 At the http://www.w3schools.com/html/default.asp website, work through the following sections: 1. Home 2. Intro 3. Elements 4. Basic Tags Make sure you look at the examples provided on w3schools. Using the TextEdit program, make a simple web page that provides a brief history about you that includes an example of each the following:       Heading two paragraphs a line break centered text horizontal rule hidden comments    My History should include at least:  birthplace  schools attended  favorite activities  family pets places you have traveled favoritejoke HTML Project 2 At the http://www.w3schools.com/html/default.asp website, work through the following sections: 5. Formatting Using the TextEdit program, make a simple web page resume that includes your academics, a that provides a brief history about you that includes an example of each the following:     Formatting – include bold, strong, italics, small, subscript preformatted text address hyperlink Examples of resumes can be found at the following links: http://www.adventuresineducation.org/HighSchool/Jobs/SampleResumes/index.cfm http://jobstar.org/tools/resume/student.php Table of Contents 36 HTML Project 3 At the http://www.w3schools.com/html/default.asp website, work through the following sections: 6. Tables 7. Lists 8. HTML Forms 9. Images 10. Background 11. HTML Colors Make sure you look at the examples provided. Using the HTML Taco Editor, modify your Project 1 (your history) and include an example of each the following:      Table List Image Background Multiple Colors HTML Project 4 Work with a teacher or Mr. Moening to develop one of the Activity web pages on the Highland Park Webpage. At a minimum – you should include:  An image  Hyperlink  Document  Contact Information HTML Project 5 Using a wiki page that you establish. Create a webpage that provides a service to the community. The community service you present on your webpage does not have to be “real” , but the webpage should be accessible anywhere. You should include at least one Java Applet on your webpage. Check out the AddTwo applet on the CS1 webpage. Examples: previous students have done animal shelters, tutoring services, blood drive information, sports data clearinghouses, and swap sites Return to Table of Contents 37 Circuits Circuit Lab 1: Using Leggo my Logg-O, design and test circuits that demonstrate the following: a. b. c. d. e. T AND F is F T AND T is T F OR T is T F OR F is F NOT T is F Save your work in a .dat file named CL1. When you are done you should have five different circuits on your screen. Circuit Lab 2: Part 1: Build a simple NOR circuit using the NOR gate and two switches and a light – test your circuit and record results with a table as below: Switch 1 False (off) False True True Switch 2 False (off) True (on) False True NOR Light (on or off) Part 2: Build your own version of a NOR (not OR) circuit without using the NOR gate provided by Logg-O. Your circuit should have two switches and one light. The light should turn on when: A OR B is FALSE. The light should remain off when A OR B is TRUE. Your new circuit should give you the same results as in Part 1. Return to Table of Contents 38 Circuit Lab 3: Part 1: Build a simple XOR circuit using the XOR gate and two switches and a light – test your circuit and record results with a table as below: Switch 1 False (off) False True True Switch 2 False (off) True (on) False True A XOR B Light (on or off) Part 2: Build your own version of a XOR (Exclusive OR) circuit without using the XOR gate provided by Logg-O. Your circuit will need two switches and one light and other gates. Notice, in building your circuit that A XOR B is equivalent to: (A OR B) AND (NOT (A) OR NOT (B)). Your new circuit should give you the same results as in Part 1. Warning: The circuits described below are not provided directly by Logg-O. The only way to "test" these circuits is to compare their performance for all possible combinations of inputs to their truth tables. Circuit Lab 4: Build and test a three-way AND circuit that accepts three inputs from switches (call them A, B, and C) and turns its one output light ON only when all three switches are ON. Otherwise, its output light should be OFF. Use the truth table below to verify your circuit. Switch A F F F F T T T T Switch B F F T T F F T T Switch C F T F T F T F T Output Light Off Off Off Off Off Off Off On Return to Table of Contents 39 Circuit Lab 5: Build and test a three-way OR circuit that accepts three inputs from switches (A, B, and C), and turns on its one output light whenever at least one of the switches is ON. Use the truth table below to verify your circuit. Switch A F F F F T T T T Switch B F F T T F F T T Switch C F T F T F T F T Output Light Off On On On On On On On Circuit Lab 6: 3 bit example Build and test a circuit that accepts three inputs from switches (A, B, and C), and turns on its one output light according to the table below. Use the truth table below to verify your circuit. A K-Map might help. Switch A F F F F T T T T Switch B F F T T F F T T Switch C F T F T F T F T Output Light Off On Off On Off On On On Circuit Lab 7: 3 bit example Build and test a circuit that accepts three inputs from switches (A, B, and C), and turns on its one output light according to the table below. Use the truth table below to verify your circuit. A K-Map might help. Switch A F F F F T T T T Switch B F F T T F F T T Switch C F T F T F T F T Output Light Off Off On Off On Off On Off Return to Table of Contents 40 Circuit Lab 8: 3 bit example Build and test a circuit that accepts three inputs from switches (A, B, and C), and turns on its one output light according to the table below. Use the truth table below. Switch A F F F F T T T T Switch B F F T T F F T T Switch C F T F T F T F T Output Light Off On Off On Off On Off On Circuit Lab 9: Half Adder Use Logg-O to build a 1-bit half adder using AND, OR, and NOT gates, as described in in class. Test it using all possible combinations of inputs. Bit 1 0 0 1 1 Bit 2 0 1 0 1 Result 0 1 1 0 Carry Out 0 0 0 1 Circuit Lab 10: Full Adder Fill in the table to and build a full adder using AND, OR, and NOT gates. Bit 2 Carry In Result Carry Out Bit 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 1 0 1 0 1 0 1 Circuit Lab 11: Burglar Alarm Use Logg-O to create a circuit that will function as a burglar alarm. The alarm should activate only when it is turned on and when a door, window or both is open. Alarm Set Door Window Alarm Signal Return to Table of Contents 41 Return to Table of Contents 42 Predator/Prey Programming Project Objectives: Investigate the wolf/moose dynamics on Isle Royal and write a program to model the population of each and display the information in a userfriendly interface. This project will require the student to understand fundamental object oriented programming techniques, sorting algorithms, and searching algorithms. The model will incorporate as many real-life factors as possible. Examining the Problem First conduct some background research on Moose and Wolves on Isle Royal including the following:  read the background information below  http://www.isleroyalewolf.org/wolfhome/home.html  http://www.wolfmoose.mtu.edu/  google map Isle Royale for background Programming 1. Create Simple Moose and Wolf Classes with minimal methods (set and get) 2. Create the Pack and Herd Class with location for the Pack 3. Create the IsleRoyal Class that creates a herd and a pack 4. Display a list of existing moose and wolves (CLI is ok) 5. Display the Pack and Moose icons on the island (GUI) 6. Get the movement methods functional 7. Get the interaction and related methods functional 8. Allow for reproduction of moose and wolves (investigate rates first) 9. Simulate a 20-year cycle with yearly population reports Background Information: Isle Royale is the largest island within Lake Superior. Located 15 miles from the shores of Ontario, the island encompasses 130 square miles of land area. Within the island are a variety of forest types and habitats including boreal forest, maple birch forest, cedar swamps, small areas of black spruce and tamarack bogs. Over 30 separate lakes are found on the island, a few open meadows, fens and some short narrow creeks. The island, surrounded by Lake Superior since the glaciers receded about 10,000 years ago, supports few of the mammals found on the mainland, as migration across Lake Superior is very difficult. These Isle Royale mammals include moose, wolf, deer mouse, muskrat, red squirrel, snowshoe hare, beaver, otter, red fox and 4 species of bats. Previously, the island supported woodland caribou, coyote and lynx. Woodland caribou went extinct around 1930, coyotes died out after the wolves crossed to the island, and it is believed that lynx are extinct. The island enjoys a protected status as a wilderness area, since being designated a National Park in 1931. It is believed moose migrated to the island shortly after the turn of the century. Most probably they swam across Lake Superior from nearby Ontario. It is not uncommon Return to Table of Contents 43 to spot moose swimming in the big lake, and one was reported 22 miles from shore by a National Park Service boat crossing the lake. Lake Superior seldom freezes over, but in the late 1940's there was a severe winter when an ice bridge formed from Ontario to the island. It is believed at that time a group of 4 wolves crossed the ice to the island. All wolves presently on Isle Royale are direct descendants from a female wolf who crossed that ice bridge. Wolves are commonly spotted on the ice of Lake Superior, and one researcher watched as one pack wandered several miles from the island before finally returning to Isle Royale. The word moose is a shorter version of an Indian word Ah-moose, which means browser. During winter period’s moose emigrate to the Northeast part of the island where balsam fir is common. They readily eat the stems of these trees that are not buried by snow and are within their reach. In winter, moose also browse on stems of aspen and birch, if available. Winter is a challenging time for moose. Tree stems are less nutritious than summer foods, and by late winter, moose often suffer from outbreaks of the Winter Tick. This tick attacks only moose, and during severe outbreaks one moose can support many thousands of ticks. To rid themselves of these irritating ticks, moose rub against trees and consequently lose much of their winter coat as well, making them more vulnerable to extreme cold. During summer periods, moose prefer to browse on green leafy vegetation and they have such an impact on the island's vegetation that plants that moose find unpalatable are the most common. Aquatic plants like water lilies are a favorite of moose and moose are often found in lakes foraging, sometimes completing submerging to get at the succulent aquatic plants. The island has supported from 500 to 3,000 moose throughout its history. It is believed that the moose population fluctuated even more prior to the arrival of wolves on the island. Wolves are the largest predators found on the island. Living in packs, they consist of an alpha male and female along with their pups, sometimes from several generations. The island has generally had only 2 to 3 packs of wolves throughout its history. The wolf's digestive tract is supremely adapted to digest meat, which makes up almost the entirety of its diet. Because of the pack nature of wolves, they need a lot of protein to sustain them and they must focus on large prey animals. Research has shown that wolves usually kill moose less than one year of age, or those that are over 10 years of age. In fact, moose in their prime often do not even run from wolves, but stand their ground, forcing the wolves to move on to locate easier prey. In spring, before the moose cows have calved, beaver makes up a part of the wolf's diet, beaver are captured while on land to cut trees to repair their dams and lodges after damage from spring run-off. The island has proved to be an ideal place to study predator/prey relationships between moose and wolves. The island is completely protected from development because it is part of Isle Royale National Park. It is surrounded entirely by Lake Superior, and there are few mammal species within the park. In fact, this is the longest predator/prey study completed and it is still on going. The study began in the 1950’s with Durward Allen, Purdue University and is continued today by Rolf O. Peterson, Michigan Technological University. Rolf Peterson believes Isle Royale wolves will become extinct, without human intervention, as a result of an “extinction vortex”. Mitochondrial genetic analysis has revealed that all wolves are descendants from one female wolf in the late 1940’s. As a result of inbreeding, animals often become less fertile or sterile, leading to smaller populations of animals. This increases inbreeding that further decreases genetic variability until extinction occurs because of lost fertility. Genetic analysis reveals that Isle Royale wolves already have 50% of the genetic variability of wolves on the mainland. Recent reproductive success by wolves suggests that as of present, the genetic loss is not having any deleterious effect on wolf reproduction. Return to Table of Contents 44 Wolves suffer from diseases that are common in dogs. For that reason dogs are not allowed on the Island. Research has shown that wolves have been exposed to Canine Parvovirus a disease that often kills wolf pups and dog puppies. Two of the isla nd's wolves were checked for Canine Parvovirus in 1998 and no evidence was found for the disease. Return to Table of Contents 45 Isle Royale Data: year # of moose 1960 576 1961 580 1962 600 1963 650 1964 675 1965 720 1966 800 1967 950 1968 1200 1969 1225 1970 1350 1971 1425 1972 1400 1973 1430 1974 1350 1975 1250 1976 1125 1977 975 1978 1000 1979 900 1980 850 1981 800 1982 700 1983 900 1984 811 1985 1062 1986 1025 1987 1380 1988 1653 1989 1397 1990 1216 1991 1313 1992 1600 1993 1880 1994 1800 1995 2400 1996 1200 1997 500 1998 700 1999 750 2000 850 2001 900 2002 1100 # of wolves 22 22 23 20 27 28 27 23 23 16 17 19 22 23 31 41 43 35 40 42 50 30 14 23 24 22 20 16 12 11 15 12 12 13 15 16 22 24 14 25 29 19 16 Return to Table of Contents 46 Program Design Moose Class  get/set methods for age, coordinate)  browse method - move 1/2  strength is a factor of algorithm  random disease method illness sex, health, strength, location (x and y mile in a random direction every day age and health - class will choose an 5% of die every 365 days due to random Herd Class  includes an array of moose (1500 maximum)  if herd size is >1500 a decimate method is called  decimate method eliminates the bottom 20% based on strength  reproduction method based on herd health/size Wolf Class * get/set methods include age, sex, health, strength, * strength is a factor of age and health - class will choose an algorithm * random disease method - 5% of die every 365 days due to random illness Pack Class * includes an array of wolves (30 max) - start with 5 * get/set methods for location (x and y coordinate) * get/set methods for health (max value is 20, minus 1 every day without food) * reproduction - class will choose an algorithm * movement - initially moves in a random direction - 4 miles in one day * pack size is limited to 10 - more than ten make a new pack IsleRoyal Class  x coordinates from 0 to 45 miles  y coordinates from 0 to 8 miles  wind - varies - 60% of time from the NW (changes randomly)  checkLocation method - checks if Pack is downwind of a moose within 1 mile o must compare the location of each moose to the pack o calls interaction method if downwind of moose within 1 mile  interactionMethod - receives a Pack and moose Return to Table of Contents 47 o contains an if statement to determine if moose survives (based on health of pack and moose) o all parties loose strength in a interaction – can be fatal for either party o call a set packHealth, set mooseHealth, set packLocation Interface Class * a GUI interface to view the location of the Pack and the Moose * Moose icon: size depends on Moose health (larger icon for better health) * Pack icon size depends * button to print current status * Update button (increments time by 1 day) o health of wolf decreases each day without food (-1) o check herd size (problems greater than 1000) o check wolf health (some could starve) o display location o call more movement of moose and pack o check for interaction Misc Info 1 pack (max about ten wolves) must feed on approximately 20 moose in a year 1 wolf needs approximately 2 moose per year (feed on pack kills) Moose Population >1,000 causes significant starvation Moose typically do not live long past their 10th birthday odd of pack attach bringing down a moose is not 100% moose weight = feeds pack for roughly 10 days pack attack on healthy moose - 10% chance of wolf death, 5% chance of moose death Return to Table of Contents 48 Java Cheat Sheet Simple Printing Examples System.out.print(“Enter the score”); System.out.println(“Try again”); (new line) System.out.println(“The answer is “+ 42); for loop example for (countDown=3;countDown>=0;countDown--) { System.out.println(countDown); System.out.println("and counting."); } while loop example while (x<10) { System.out.println(x); x = x+1; } if examples if ( xCoord > 800 ) addition = -5; if with multiple actions (braces) if ( xCoord > 800 ) { xAddition = -5; forwards = true; //Boolean variable } if with else if ( hungry) //hunger is Boolean variable System.out.println("Buy the cookie!" ); else System.out.println("Buy the App" ); Using and, or, not with if “and” is represented in Java as && “or” is represented in Java as | | “not” is represented in Java as ! for example if (x>10 && y<10) System.out.println(“good shot”); Java Variables Integers (whole numbers) int x = 1; Real Numbers (think decimals) double x = 20.5 Strings (text): String name = “Erin”; Single Characters (single quotes): Char letter=’A’; Boolean values (true or false) Boolean isPrime= true; Arrays int theArray[] = new int[10]; 1 dimensional Useful Math Class Methods Result Math.abs(-7) 7 Math.pow(2.0,3.0) 8.0 Math.random() 0y // x is greater than y x <= y // x is less than or equal to y x == y // x equals y x != y // x is not equal to y Increment and Decrement Operators count++; //increase the value of count by 1 count--; // decrease the value of count by 1 count+2; // increase the value of count by 2 String Methods x = name.length(); boolean match =name.equals(inputName); name = name.toLowerCase(); char x = charAt(3); Java Escape Characters \n new line \t horizontal tab \\ backslash – prints a backslash \” prints a double quote System.out.println("Hello\nnext\nLine"); Return to Table of Contents 49 Java Graphics Cheat Sheet Line canvas.drawLine(75, 200, 75, 350); Rectangle canvas.fillRect(x, y, width, height); //fills in a rectangle canvas.drawRect(x, y, width, height); //draws the outline of a rectangle Oval/Circle canvas.fillOval(x, y, width, height); canvas.drawOval(x, y, width, height); //fills in an oval //draws the outline of an oval Arc canvas.fillArc(x, y, width, height, startAngle, sweepOfAngle); Color canvas.setColor(Color.blue); canvas.setColor(new Color(215, 215, 215)); meter //numbers from 0 to 255 – use the digital color Background Color setBackground(Color.red); setBackground(new Color(0,40,200); Write Text on Screen canvas.drawString ("hello HP", x, y); Return to Table of Contents 50 Mouse and Keyboard Input Example import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyBoardMouseApplet extends JApplet implements KeyListener, MouseListener, MouseMotionListener { int width, height; int x, y; char letter = 't'; String word = " "; public void init() { width = getSize().width; //get size of window height = getSize().height; setBackground( Color.black ); x = width/2; //start x and y in the middle of screen y = height/2; // turn the Listener on to receive Listener objects addKeyListener( this ); addMouseListener( this ); addMouseMotionListener( this ); } public void paint( Graphics g ) { g.setColor( Color.black ); g.fillRect(0,0,800,600); g.setColor( Color.green ); g.fillRect(x-50,y-50,5,5); g.setColor( Color.blue ); g.fillRect(x+50,y+50,5,5); g.drawString(word,x+50,y-50); } //KeyListener Methods - must include all even if you don't use them public void keyPressed( KeyEvent e ) { } public void keyReleased( KeyEvent e ) { } public void keyTyped( KeyEvent e ) { letter = e.getKeyChar(); word = letter+word; repaint(); e.consume(); } Return to Table of Contents 51 //MouseListener Methods - must include all public void mouseEntered( MouseEvent e ) { } public void mouseExited( MouseEvent e ) { } public void mousePressed( MouseEvent e ) { } public void mouseReleased( MouseEvent e ) { } public void mouseClicked( MouseEvent e ) {} //MouseMotionListener Methods - must include all public void mouseMoved( MouseEvent e ) //look up MouseEvent in API for methods like e.getX() { x = e.getX(); y = e.getY(); repaint(); e.consume(); } public void mouseDragged( MouseEvent e ) { } } Return to Table of Contents 52 Return to Table of Contents 53

Related docs
Java Cheat Sheet
Views: 128  |  Downloads: 20
Java Cheat Sheet
Views: 40  |  Downloads: 9
HP JAVA Cheat Sheet
Views: 17  |  Downloads: 4
Java Cheat Sheet
Views: 0  |  Downloads: 0
Java Cheat Sheet
Views: 41  |  Downloads: 3
Java Cheat Sheet
Views: 42  |  Downloads: 3
Basic Java Cheat Sheet
Views: 305  |  Downloads: 16
HP JAVA Cheat Sheet
Views: 1  |  Downloads: 0
Java Cheat Sheet- Abbreviated Version
Views: 10  |  Downloads: 4
JavaDoc Cheat Sheet
Views: 106  |  Downloads: 0
SWINGAWT CHEAT SHEET
Views: 22  |  Downloads: 1
premium docs
Other docs by armani11
Termination Notice Excessive Absences
Views: 1136  |  Downloads: 21
Form 2441 Child and Dependent Care Expenses
Views: 348  |  Downloads: 2
Halliburton Co Ammendments and Bylaws
Views: 126  |  Downloads: 0
Job Satisfaction Feedback Form
Views: 771  |  Downloads: 48
Sample Bylaws
Views: 501  |  Downloads: 29
ASSIGNMENT OF MONEY DUE
Views: 230  |  Downloads: 2
Board Resolution Declaring Stock Dividend
Views: 210  |  Downloads: 2
CorpDocs-Articles of Incorporation California
Views: 341  |  Downloads: 21
TRAVEL CHECKLIST
Views: 507  |  Downloads: 56
Adverse Representation
Views: 159  |  Downloads: 1