Program Statement Avoid Spaghetti Programming Program Statement.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Java Overview CS2336: Computer Science II1. First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Section 5.1 Keyboard Input.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Java Programming: From the Ground Up
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Review of Math Class Methods abssqrt minmax powround ceilfloor.
George Boole More than 150 years ago, there was a mathematician named George Boole, who took statements and wrote them in a precise format, such that.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.
Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
George Boole More than 150 years ago, there was a mathematician named George Boole, who took statements and wrote them in a precise format, such that.
Lec 4: while loop and do-while loop. Review from last week if Statements if (num < 0.5){...println("heads"); } if –else Statements if (num < 0.5){...println("heads");
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Flow of Control Chapter 3 Flow of control Branching Loops
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Chapter 4: Control Structures SELECTION STATEMENTS.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Review of Math Class Methods abssqrt minmax powround ceilfloor.
Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.
Visual Classes 1 Class: Bug 5 Objects: All Bug Objects.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
// Java0501.java // This program (and the next few programs) demonstrate user keyboard input // during program execution. This particular program demonstrates.
Chapter 5: Control Structures II
Loop Structures.
PowerPoint Presentation From Materials Created
Java Programming: Guided Learning with Early Objects
Chapter 5: Control Structures II
PowerPoint Presentation Authors of Exposure Java
PowerPoint Presentation Authors of Exposure Java
MSIS 655 Advanced Business Applications Programming
Java Programming Loops
Java Programming Control Structures Part 1
Section 6.2 Classes & Objects.
Java Programming Loops
Just Enough Java 17-May-19.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

Program Statement Avoid Spaghetti Programming Program Statement

Program Flow Program Flow follows the exact sequence of listed program statements, unless directed otherwise by a Java control structure.

Types of Control Structures Simple Sequence Selection also called: -Decision Making -Conditional Branching -Alternation Repetition also called: -Looping -Iteration

Simple Sequence Program Statement

One-Way Selection Program Statement Condition True False

Two-Way Selection Program Statement Condition TrueFalse Program Statement

Multiple-Way Selection Program Statement Condition True False Program StatementCondition True False Program StatementCondition True False

Repetition Program Statement Condition True False Program Statement

Conditional Statement Definition A conditional statement is a program expression that evaluates to true or false. Most conditional statements require a relational operator. All conditions must be placed inside (parentheses).

Relational Operators NameOperatorExpressionEvaluates Equals == 5 == 5 K == 10 true depends Not Equals != 50 != != 100 true false Less than < 100 < 200 P < Q true depends Greater than > 100 > 200 P > Q false depends Less than or equals <= 25 <= <= 25 true Greater than or equals >= 1000 >= 1000 K >= (P + Q) true depends

Important Note: The relational operators shown on the previous slide will be used in the Java example programs that demonstrate the different control structures. Be careful not to confuse the equality operator ( = = ) with the assignment operator ( = ). Before we demonstrate Control Structures, we will look at a few examples of Program Input to make the Control Structures examples more meaningful.

// Java0501.java // This program demonstrates user keyboard input during program // execution. // Many program features will be used that will be explained later. import java.util.Scanner; // Line 1 public class Java0501 { public static void main (String args[]) { Scanner input = new Scanner(System.in); // Line 2 System.out.println("\nJAVA0501.JAVA\n"); System.out.print("Enter name ===>> "); // Line 3 String name = input.nextLine(); // Line 4 System.out.println("Name Entered: " + name); System.out.println(); }

// Java0502.java // This program demonstrates how to use for three separate String // keyboard inputs. import java.util.Scanner; public class Java0502 { public static void main (String args[]) { System.out.println("\nJAVA0502.JAVA\n"); Scanner input = new Scanner(System.in); System.out.print("Enter Line 1 ===>> "); String input1 = input.nextLine(); System.out.print("Enter Line 2 ===>> "); String input2 = input.nextLine(); System.out.print("Enter Line 3 ===>> "); String input3 = input.nextLine(); System.out.println(); System.out.println(input1); System.out.println(input2); System.out.println(input3); System.out.println(); }

// Java0503.java // This program demonstrates objects concatenation with // keyboard entered data. import java.util.Scanner; public class Java0503 { public static void main (String args[]) { System.out.println("\nJAVA0503.JAVA\n"); Scanner input = new Scanner(System.in); System.out.print("Enter 1st Number ===>> "); String number1 = input.nextLine(); System.out.print("Enter 2nd Number ===>> "); String number2 = input.nextLine(); String sum = number1 + number2 ; System.out.println(); System.out.println(number1 + " + " + number2 + " = " + sum); System.out.println(); }

// Java0504.java // This program uses the method to enter integers from the keyboard. // It is now possible to correctly add the two numbers. import java.util.Scanner; public class Java0504 { public static void main (String args[]) { System.out.println("\nJAVA0504.JAVA\n"); Scanner input = new Scanner(System.in); System.out.print("Enter 1st Number ===>> "); int number1 = input.nextInt(); System.out.print("Enter 2nd Number ===>> "); int number2 = input.nextInt(); int sum = number1 + number2; System.out.println(); System.out.println(number1 + " + " + number2 + " = " + sum); System.out.println(); }

// Java0505.java // This program demonstrates how to use for three separate double // keyboard inputs, which are used to display the mean. import java.util.Scanner; public class Java0505 { public static void main (String args[]) { System.out.println("\nJAVA0505.JAVA\n"); Scanner input = new Scanner(System.in); System.out.print("Enter Number 1 ===>> "); double n1 = input.nextDouble(); System.out.print("Enter Number 2 ===>> "); double n2 = input.nextDouble(); System.out.print("Enter Number 3 ===>> "); double n3 = input.nextDouble(); System.out.println(); System.out.println(n1); System.out.println(n2); System.out.println(n3); double mean = (n1+n2+n3)/3; System.out.println(); System.out.println("The mean is " + mean); System.out.println(); }

Scanner class Input Methods nextLine() is used to enter string information. nextInt() is used to enter integer information. nextDouble() is used to enter real# information.

Java 5.0 Exposure Java 2006 includes features of the new Java version created by Sun MicroSystems. This new version is called Java 5.0 or perhaps Java The naming of Java versions can be confusion. The text keyboard input section with the Scanner class is the first example of a Java 5.0 feature. Students new to Java will hardly recognize new features from old features. Teachers and students need to be alert that previous Java Software Development Kits (SDKs) or Java Development Kits (JDKs) will not recognize these new features. If such is the case go to the Java download site shown below:

AP Exam Alert The May 2007 AP Computer Science Examination will be the first to include various Java 5.0 material. The Scanner class will not be tested on the 2007 examination. Starting with the first Java examination, the College Board decided not to test any type of Java input features, which also now includes the new keyboard style input with the Scanner class.

// Java0506.java // This program demonstrates one-way selection with. // Run the program twice. // First with Sales equals to 300,000 and a second time with Sales equals 500,000. import java.util.Scanner; public class Java0506 { public static void main (String args[]) { System.out.println("\nJAVA0506.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter Sales ===>> "); double sales = keyboard.nextDouble(); double bonus = ; if (sales >= ) bonus += 500.0; System.out.println("Yearly bonus: " + bonus); System.out.println(); }

Indentation Rule: Java syntax uses freeform program style. Program statements may be placed on multiple lines with or without indentation. By convention, control structures and their conditional statements are placed on one line. The program statement that is executed, if the condition is true, is placed on the next line, and indented below the conditional statement. if(Sales >= ) Bonus += 500; if(Sales >=500000) Bonus += 500;

// Java0507.java // This program demonstrates one-way selection with. // It also shows that only one statement is controlled. // Run the program twice. First with Sales equals to 300,000 // and then a second time with Sales equals to 500,000. import java.util.Scanner; public class Java0507 { public static void main (String args[]) { System.out.println("\nJAVA0507.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter Sales ===>> "); Double sales = keyboard.nextDouble(); double bonus = ; if (sales >= ) bonus += 500.0; System.out.println("Your sales >= 500,000.00"); System.out.println("You will receive extra bonus."); System.out.println ("Yearly bonus: " + bonus); System.out.println(); }

// Java0508.java // This program demonstrates one-way selection with. It fixes the // logic problem of the previous program with block structure by using braces. import java.util.Scanner; public class Java0508 { public static void main (String args[]) { System.out.println("\nJAVA0508.JAVA\n"); Scanner = new Scanner(System.in); System.out.print("Enter Sales ===>> "); double sales = keyboard.nextDouble(); double bonus = ; if (sales >= ) { bonus += 500.0; System.out.println("Your sales >= 500,000.00"); System.out.println("You will receive extra bonus."); } System.out.println("Yearly bonus: " + bonus); System.out.println(); }

One-Way Selection Syntax One-Way selection general syntax: if (condition true) execute program statement if (Counter > 100) System.out.println("Counter exceeds 100"); Use braces { } and block structure to control multiple program statements. if (Savings >= 10000) { System.out.println("It’s skiing time"); System.out.println("Let’s pack"); System.out.println("Remember your skis"); }

// Java0509.java // This program demonstrates two-way selection with. import java.util.Scanner; public class Java0509 { public static void main (String args[]) { System.out.println("\nJAVA0509.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter SAT ===>> "); int sat = keyboard.nextInt(); if (sat >= 1100) System.out.println("You are admitted"); else System.out.println("You are not admitted"); System.out.println(); }

// Java0510.java // This program demonstrates two-way selection with. // Multiple statements require the use of block structure. import java.util.Scanner; public class Java0510 { public static void main (String args[]) { System.out.println("\nJAVA0510.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter SAT ===>> "); int sat = keyboard.nextInt(); if (sat >= 1100) { System.out.println("You are admitted"); System.out.println("Orientation will start in June"); } else { System.out.println("You are not admitted"); System.out.println("Please try again when your SAT improves."); } System.out.println(); }

Two-Way Selection Syntax Two-Way selection general syntax: if (condition true) execute first program statement else // when condition is false execute second program statement if (GPA >= 90.0) System.out.println ( "You’re an honor graduate"); else System.out.println ("You’re not an honor graduate");

// Java0511.java // This program demonstrates multi-way selection with and. // This program compiles, but displays illogical output. import java.util.Scanner; public class Java0511 { public static void main (String args[]) { System.out.println("\nJAVA0511.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter Letter Grade ===>> "); String temp = keyboard.nextLine(); char grade = temp.charAt(0); // converts 1st letter in the String to a char switch (grade) { case 'A' : System.out.println(" Average"); case 'B' : System.out.println(" Average"); case 'C' : System.out.println(" Average"); case 'D' : System.out.println(" Average"); case 'F' : System.out.println("Below 60 Average"); } System.out.println(); }

// Java0512.java // This program demonstrates multi-way selection with and. // This program adds and. // The use of is required for logical output. import java.Scanner; public class Java0512 { public static void main (String args[]) { System.out.println("\nJAVA0512.JAVA\n"); Scanner keyboard = new Scanner(System.in); System.out.print("Enter Letter Grade ===>> "); String temp = keyboard.nextLine(); char grade = temp.charAt(0); // converts 1st letter in the String to a char switch (grade) { case 'A': System.out.println(" Average"); break; case 'B': System.out.println(" Average"); break; case 'C': System.out.println(" Average"); break; case 'D': System.out.println(" Average"); break; case 'F': System.out.println("Below 60 Average"); break; default : System.out.println("No Match Found"); } System.out.println(); }

Multiple-Way Selection Syntax Multiple-way selection general syntax switch(selectionVariable) { case selectionConstant: program statement; break; default : program statement; } switch(courseGrade) { case ’A’: points = 4; break; case ’B’: points = 3; break; case ’C’: points = 2; break; case ’D’: points = 1; break; case ’F’: points = 0; break; default : points = 0; } The default statement is used to handle the situation when a proper match is not found. Frequently an error message is used to indicate that no match was found.

Multiple-Way Selection Block-Structure Syntax NO-NO Example The extra braces accomplish nothing and even prevent the break commands from working. switch(courseGrade) { case ’A’:{ points = 4; System.out.println(“Excellent!”); break; } case ’B’:{ points = 3; System.out.println(“Good”); break; } case ’C’:{ points = 2; System.out.println(“Fair”); break; } case ’D’:{ points = 1; System.out.println(“Poor”); break; } case ’F’:{ points = 0; System.out.println(“Bad”); break; } default : points = 0; }

Multiple-Way Selection Block-Structure Syntax Yes-Yes Example The switch statement is the only control structure that does not use braces for block structure. The break command at the end of each case is all it needs to keep each case separate. switch(courseGrade) { case ’A’:points = 4; System.out.println(“Excellent!”); break; case ’B’:points = 3; System.out.println(“Good”); break; case ’C’:points = 2; System.out.println(“Fair”); break; case ’D’:points = 1; System.out.println(“Poor”); break; case ’F’:points = 0; System.out.println(“Bad”); break; default : points = 0; }

// Java0513.java // This program displays 40 identical lines very inefficiently // with 40 separate println statements. public class Java0513 { public static void main(String args[]) { System.out.println("\nJAVA0513.JAVA\n"); System.out.println("Eat at Joe's friendly diner for the best lunch value"); ::::::::::::::::

// Java0514.java // This program displays 40 identical lines efficiently // with one println statement and a loop structure. public class Java0514 { public static void main(String args[]) { System.out.println("\nJAVA0514.JAVA\n"); int k; for (k = 1; k <= 40; k++) System.out.println("EAT AT JOE'S FRIENDLY DINER FOR THE BEST LUNCH VALUE"); System.out.println(); }

// Java0515.java // This program displays consecutive numbers 1 through 15. // It also shows how the loop control variable may be // defined inside the program statement. public class Java0515 { public static void main(String args[]) { System.out.println("\nJAVA0515.JAVA\n"); for (int k = 1; k <= 15; k++) System.out.print(k + " "); System.out.println(); }

// Java0516.java // This program demonstrates how to use block structure // with a loop control structure. public class Java0516 { public static void main(String args[]) { System.out.println("\nJAVA0516.JAVA\n"); for (int k = 1; k <= 5; k++) { System.out.println("####################################"); System.out.println("Line Number " + k); } System.out.println(); }

// Java0517.java // This program displays various counting schemes. // It also demonstrates the versatility of the loop. public class Java0517 { public static void main(String args[]) { System.out.println("\nJAVA0517.JAVA\n"); for (int p = 1; p <= 15; p++) System.out.print(p + " "); System.out.println(); for (int q = 1; q <= 15; q+=3) System.out.print(q + " "); System.out.println(); for (int r = 15; r >= 1; r--) System.out.print(r + " "); System.out.println(); for (double s = 0; s <= 3; s+=0.5) System.out.print(s + " "); System.out.println(); for (char t = 'A'; t <= 'Z'; t++) System.out.print(t + " "); System.out.println("\n\n"); }

Repetion Control Structures With for Java has a variety of control structures for repetition. Other computer science terms for repetition are looping & iteration. Fixed iteration is done with the for loop structure. for loop syntax: for (Part1; Part2; Part3) loop body; The for loop has three distinct parts: Part1 initializes the Loop Control Variable (LCV). Part2 sets the exit condition for the loop. Part3 determines how the LCV changes. for (k = 1; k <= 10; k++) System.out.println("Java is 10 times more fun");

Note to Students with Advanced Knowledge It is possible to treat the for loop structure like a conditional loop that is not fixed. In fact, a for loop can be designed to behave exactly like a while loop. It is my intention to use and treat a for loop like a fixed iteration loop and use the while loop and do...while loop for other repetition situations. This approach is less likely to cause confusion. At some later date, when you are comfortable with all the control structures, you can use them in any appropriate manner. If this does not make sense to you, GOOD, ignore this little summary box, and move on.

// Java0518.java This program demonstrates the precondition loop. public class Java0518 { public static void main(String args[]) { System.out.println("\nJAVA0518.JAVA\n"); int p = 1; int q = 1; int r = 15; double s = 0; char t = 'A'; while (p <= 15){ System.out.print(p + " "); p++; } System.out.println(); while (q <= 15){ q++; System.out.print(q + " "); } System.out.println(); while (r >= 0) { System.out.print(r + " "); r--; } System.out.println(); while (s < 3) { System.out.print(s + " "); s += 0.5; } System.out.println(); while (t <= 'Z'){ System.out.print(t + " "); t++; } System.out.println("\n\n"); }

Repetion Control Structures With while while loop syntax: initialize condition variable while(condition is true) loop body alter condition variable in loop body x = 0; // initialize condition variable while(x < 10) { x++; // alter condition variable System.out.println("x = " + x); }

Program Segment NoNo #1 Program Segment YesYes #1 int X = 0; while(X < 10) System.out.println(X); int X = 0; while(X < 10) { X++; System.out.println(X); } The loop condition variable, X, never changes. The loop will not exit. The loop condition variable, X, changes. The loop exits when X reaches 10.

Program Segment NoNo #2 Program Segment YesYes #2 int X; while(X < 10) { X++; System.out.println(X); } int X = 0; while(X < 10) { X++; System.out.println(X); } The loop condition variable, X, is never initialized. This program will not compile in Java. The loop condition variable, X, is initialized. The program will compile and execute normally.

// Java0519.java This program demonstrates the postcondition loop. public class Java0519 { public static void main(String args[]) { System.out.println("\nJAVA0519.JAVA\n"); int p = 1; int q = 1; int r = 15; double s = 0; char t = 'A'; do { System.out.print(p + " "); p++; } while (p <= 15); System.out.println(); do { System.out.print(q + " "); q+=3; } while (q <= 15); System.out.println(); do { System.out.print(r + " "); r--; } while (r >= 0); System.out.println(); do { System.out.print(s + " "); s += 0.5; } while (s < 3); System.out.println(); do { System.out.print(t + " "); t++; } while (t <= 'Z'); System.out.println("\n\n"); }

Important Note About Worked Out Exercises and Control Structures with Graphics If you are following along in the textbook you will notice the next section is called Worked out Exercises. The PowerPoint slides for these are in a separate file called EJ-WOExSli05.ppt. This PowerPoint presentation concludes with Control Structures with Graphics which shows how Graphics programs are greatly enhanced with control structures.

// Java0520.java // This program shows how a control structure can be // used with graphics. import java.awt.*; import java.applet.*; public class Java0520 extends Applet { public void paint(Graphics g) { for (int side = 50; side < 500; side +=10) g.drawRect(50,50,side,side); }

// Java0521.java // This program is another example of displaying multiple graphics rectangles // using a loop control structure. import java.awt.*; import java.applet.*; public class Java0521 extends Applet { public void paint(Graphics g) { int x = 375; int y = 275; int side = 50; for (int k = 1; k <= 25; k++) { g.drawRect(x,y,side,side); x -= 10; y -= 10; side += 20; }

// Java0522.java // This program demonstrates how to draw multiple lines // easily with a loop structure. import java.awt.*; import java.applet.*; public class Java0522 extends Applet { public void paint(Graphics g) { g.drawRect(50,50,500,500); for (int x = 50; x <= 550; x += 10) g.drawLine(x,50,600-x,550); }

// Java0523.java // This program continues the pattern started in Java0522.java // to create an interesting pattern. import java.awt.*; import java.applet.*; public class Java0523 extends Applet { public void paint(Graphics g) { g.drawRect(50,50,500,500); for (int x = 50; x <= 550; x += 10) g.drawLine(x,50,600-x,550); for (int y = 50; y <= 550; y += 10) g.drawLine(50,y,550,600-y); }

// Java0524.java // This program introduces animation using the "draw and erase“ // method. import java.awt.*; import java.applet.*; public class Java0524 extends Applet { public void paint(Graphics g) { for (int x = 0; x < 780; x += 5) { g.setColor(Color.black); g.fillOval(x,300,20,20); for (long delay = 1; delay < ; delay++) ; g.setColor(Color.white); g.fillOval(x,300,20,20); } Usually, a semicolon is not put at the end of a for statement. In this case we simply want to create a short time delay. This is done by repeating nothing 10,000,000 times.

// Java0525.java // This program demonstrates an animated snowman. import java.awt.*; import java.applet.*; public class Java0525 extends Applet { public void paint(Graphics g) { g.setColor(Color.black); g.fillRect(0,0,800,600); for (int x = 0; x < 780; x += 5) { g.setColor(Color.white); g.fillOval(x,300,20,20); g.fillOval(x-6,315,32,32); g.fillOval(x-15,340,50,50); for (long delay = 1; delay < ; delay++); g.setColor(Color.black); g.fillOval(x,300,20,20); g.fillOval(x-6,315,32,32); g.fillOval(x-15,340,50,50); }

What is this for? I have noticed that several students are confused on Lab 5 which essentially combines repetition control structures with graphics. The concepts in Chapter 5 are crucial to understanding the rest of the course. These additional slides and Java programs were created to help students better understand how repetition control structures work with graphics.

One end of all of the lines is fixed at coordinate 400,300 At the other end, all of the lines have the same y-ordinate: 600

// Java0526.java // Understanding Lab 5: Demo #1 import java.awt.*; import java.applet.*; public class Java0526 extends Applet { public void paint(Graphics g) { for (int x = 0; x <= 800; x += 20) { g.drawLine(400, 300, x, 600); }

One end of all of the lines is fixed at coordinate 400,600 At the other end, all of the lines have the same y-ordinate: 0

// Java0527.java // Understanding Lab 5: Demo #2 import java.awt.*; import java.applet.*; public class Java0527 extends Applet { public void paint(Graphics g) { for (int x = 0; x <= 800; x += 20) { g.drawLine(400, 600, x, 0); }

One end of all of the lines is fixed at coordinate 0,300 At the other end, all of the lines have the same x-ordinate: 400

// Java0528.java // Understanding Lab 5: Demo #3 import java.awt.*; import java.applet.*; public class Java0528 extends Applet { public void paint(Graphics g) { for (int y = 0; y <= 600; y += 20) { g.drawLine(0,300,400,y); }

One end of all of the lines is fixed at coordinate 800,300 Just like the other half, at the other end, all of the lines have the same x-ordinate: 400

// Java0529.java // Understanding Lab 5: Demo #4 import java.awt.*; import java.applet.*; public class Java0529 extends Applet { public void paint(Graphics g) { for (int y = 0; y <= 600; y += 20) { g.drawLine(0,300,400,y); } for (int y = 0; y <= 600; y += 20) { g.drawLine(800,300,400,y); }

All of these lines start with a y-ordinate of 600 and end with an x-ordinate of 800. Not only are the lines not in the white box, some go up beyond the top of the screen.

// Java0530.java // Understanding Lab 5: Demo #5 // The red border is used to demonstrate lines being drawn in the wrong place. import java.awt.*; import java.applet.*; public class Java0530 extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(0,0,800,600); g.setColor(Color.white); g.fillRect(20,15,760,570); g.setColor(Color.black); int y = 600; for (int x = 0; x <= 800; x += 20) { g.drawLine(x,600,800,y); y-=20; }

All of these lines start with a y-ordinate of 540 and end with an x-ordinate of 740. The lines still go "through the roof" because the screen is not as tall as it is wide.

// Java0531.java // Understanding Lab 5: Demo #6 // This program takes the first step to get the lines inside the 60-pixel wide red border. import java.awt.*; import java.applet.*; public class Java0531 extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(0,0,800,600); g.setColor(Color.white); g.fillRect(60,60,680,480); g.setColor(Color.black); int y = 540; for (int x = 60; x <= 740; x += 20) { g.drawLine(x,540,740,y); y-=20; }

By altering the y-count the output looks the way we want.

// Java0532.java Understanding Lab 5: Demo #7 // This program alters the y count to adjust for the fact that the screen // is wider than it is tall. import java.awt.*; import java.applet.*; public class Java0532 extends Applet { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(0,0,800,600); g.setColor(Color.white); g.fillRect(60,60,680,480); g.setColor(Color.black); int y = 540; for (int x = 60; x <= 740; x += 20) { g.drawLine(x,540,740,y); y-=14; }