Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements

Chapter 4 Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Lambert / Osborne Objectives Use the increment and decrement operators. Use standard math methods. Use if and if-else statements to make choices. Use while and for loops to repeat a process. Construct appropriate conditions for control statements using relational operators. Detect and correct common errors involving loops. Chapter 4

2 Lambert / Osborne Fundamentals of Java 4E Vocabulary control Chapter 4 3 statements counter count-controlled loop entry-controlled loop flowchart infinite loop Lambert / Osborne iteration off-by-one

error overloading random number generator sentinel task-controlled loop Fundamentals of Java 4E Additional Operators Extended Chapter 4 Assignment Operators: An assignment operator combined with arithmetic and concatenation operators. variable op= expression; variable = variable op expression; Increment (++) and Decrement(--):

Operators increase or decrease a variables value by one. 4 Lambert / Osborne Fundamentals of Java 4E Standard Classes and Methods The Chapter 4 5 Math Class: Range of common mathematical methods. Overloading: having two methods with the same name (abs). The sqrt method sends a message to the class instead of to an object because the Math class is

static. Lambert / Osborne Fundamentals of Java 4E Standard Classes and Methods (continued) Seven methods in the Math class Chapter 4 6 Lambert / Osborne Fundamentals of Java 4E Standard Classes and Methods (continued) The Chapter 4

Random Class: Supports programs that incorporate random numbers. Programs are used to simulate random events: Coin toss, stock market, etc. Random number generator returns numbers chosen at random from a predesigned interval. 7 Lambert / Osborne Fundamentals of Java 4E Standard Classes and Methods (continued)

The Chapter 4 8 Random Class (cont): Programs that use Random class must import java.util.Random. The output from codes using the Random class is different every time it is generated. Methods in the Random class Lambert / Osborne Fundamentals of Java 4E A Visit to the Farm if-else and while are control statements. Chapter 4

while means to repeat the action as long as the set condition holds true. If means to do one thing is the condition is true, and another if the condition is false. 9 Lambert / Osborne Fundamentals of Java 4E The if and if-else Statements Java is programmer-friendly because it combines English phrasing with algebraic notations. Chapter 4

if and if-else are examples. Required elements: Semicolons: do not follow a closing brace. Braces: always in pairs; better to overuse than underuse. The exact format of the text depends on the programmer. 10 Lambert / Osborne Fundamentals of Java 4E The if and if-else Statements

(continued) Principal Forms: Chapter 4 11 Lambert / Osborne Fundamentals of Java 4E The if and if-else Statements (continued) Additional Chapter 4 Forms: The braces can be dropped if a single statement follows if or else. The condition in an if statement must be a Boolean expression.

12 Returns the value true or false. Lambert / Osborne Fundamentals of Java 4E The if and if-else Statements (continued) Flowcharts for the if and if-else statements. Chapter 4 13 Lambert / Osborne Fundamentals of Java 4E

The if and if-else Statements (continued) Relational Chapter 4 Operators: Greater than (>), equal to (==), less than or equal to (<=), not equal to (!=), etc. == distinguishes the equal-to operator from the assignment operator. In the not-equal-to operator, ! is read as no. These 14 values will either be true or false. Lambert / Osborne

Fundamentals of Java 4E The if and if-else Statements (continued) Checking Chapter 4 Input for Validity: if-else statements are commonly used to check user inputs before processing them. For example, if a user enters a negative number for a circles radius. 15 Program checks to see if the radius is >= 0. If >= 0, the radius is computed. If < 0, an error message displays. Lambert / Osborne

Fundamentals of Java 4E The while Statement Provides Chapter 4 a looping mechanism that executes statements repeatedly as long as some condition remains true. Flowchart for a while statement 16 Lambert / Osborne Fundamentals of Java 4E The while Statement (continued)

Chapter 4 17 Count-Controlled Loops: The variable cntr controls how many times the loop executes. For example, a program that computes and displays the sum of the integers between 1 and 100. Each pass of the loop is an iteration. Trace of how variables change on each iteration through a loop Lambert / Osborne Fundamentals of Java 4E The while Statement (continued)

Chapter 4 Adding Flexibility: Could vary the starting value, ending value, and increment, or ask for user input for those values. Task-controlled loop: Executes until a task is accomplished. 18 Example: find the first integer for which the sum 1+2. +n is over 1 million. The factorial of a given number (n) is the product of the numbers between 1 and n (1*2*3**n).

Lambert / Osborne Fundamentals of Java 4E The while Statement (continued) Common Chapter 4 19 Structure: All of these examples share a common structure. For the loop to terminate, each iteration must move the variables closer to satisfying the condition. Lambert / Osborne Fundamentals of Java 4E The for Statement

Combines counter initialization, a condition test, and an update in a single expression. Chapter 4 20 When the statement is executed, the counter is initialized. As long as the test yields true, the loop continues. The counter is updated at the bottom of the loop, after the statements in the body have been executed. Lambert / Osborne Fundamentals of Java 4E The for Statement (continued) Count-Controlled

Chapter 4 21 Input: Programs often need to read and process repeating inputs. Example: computing the average of a list of numbers. List length can vary. Lambert / Osborne Fundamentals of Java 4E The for Statement (continued) Declaring Chapter 4 the Loop Control Variable in a for Loop : The for loop allows the programmer to declare the loop control variable outside of and

above the loop header. Within the loop header is preferable: 22 Only visible in the body of the loop where its being used. The same name can be declared again in other for loops in the same program. Lambert / Osborne Fundamentals of Java 4E The for Statement (continued) Choosing a while Loop or a for Loop: Both are entry-controlled loops.

Chapter 4 There are two advantages to choosing a for loop. 23 A continuation condition is tested at the top of the loop on each pass to determine if the loop continues (true) or terminates (false). All of the loop information (initial setting of loop control variable, its update, and the continuation test) is within the loop header. The loop control variable of a for loop can be declared in its header. Lambert / Osborne

Fundamentals of Java 4E Nested Control Statements and the break Statement Control Chapter 4 Printing the divisors of a number, excluding 1 and the number. Determining if a number is prime. The break statement is used to get out of a loop before the condition is false. Sentinels are values that mark the end of a list. 24

statements can be nested. Use the do-while and continue statements. Lambert / Osborne Fundamentals of Java 4E Using Loops with Text Files Instead of user input from the keyboard, programs can also read input from a text file. Chapter 4 Advantages 25

Software object stored on a permanent medium, such as disk, CD, or flash memory. of input data from a file: Data set can be larger. Data can be input faster and with less chance of error. Data can be reused within the same or other programs. Lambert / Osborne Fundamentals of Java 4E Using Loops with Text Files (continued) Text Chapter 4 Files and Their Format: A text file can be created, saved, and viewed with a text editor, such as Notepad. Characters, words, numbers, or lines of text.

Whitespace characters: space, tab, or newline. Must be used to separate numbers. Must include a special character that marks the end of a file. 26 A sentinel for program loop. Lambert / Osborne Fundamentals of Java 4E Using Loops with Text Files (continued) The Chapter 4

Scanner and File Classes: Scanner class can be used for text file input. Create a scanner object by opening it in a file object. File objects are instances of the File class. 27 new File(aFileName) aFileName is the pathname or name of the file. Lambert / Osborne Fundamentals of Java 4E Using Loops with Text Files (continued) Files Chapter 4 and Exceptions: Missing or corrupted file.

I/O exception is thrown. 28 A checked exception: must acknowledge that they might be thrown and do something to recover from them. Use throws IOException to instruct the JVM to halt execution with an error message. Lambert / Osborne Fundamentals of Java 4E Using Loops with Text Files (continued) Output Chapter 4 to Text Files: Use the class PrintWriter.

Class includes print and println methods. After outputs are completed, must close the PrintWriter by adding writer.close(); 29 If the output file is not closed, no data will be saved to it. Lambert / Osborne Fundamentals of Java 4E Errors in Loops Logic errors in loops can be avoided by understanding a typical loop structure. Chapter 4

30 Initializing statements: initialize variables. Terminating condition: tested before each pass to determine if another iteration is needed. Body statements: execute with each iteration and implement the calculation in question. Update statements: change the values of the variables tested in the termination condition. Lambert / Osborne Fundamentals of Java 4E Errors in Loops (continued) Chapter 4

31 Initialization Error: When you forget to initialize the variable product. Off-by-One Error: When a loop goes around one too many or one to few times. Infinite Loop: An error in the terminating condition. Detected when a program runs slower than expected. Stop by pressing Ctrl+C. Lambert / Osborne Fundamentals of Java 4E Errors in Loops (continued)

Chapter 4 32 Error in Loop Body: Occurs in body of the loop, such as using the wrong operator. Update Error: When an update statement is in the wrong place. Effects of Limited Floating-Point Precision: Double numbers have 18 decimal points of precision. Causes problems for number such as 1/3, which is .3333 and never ends. Lambert / Osborne

Fundamentals of Java 4E Errors in Loops (continued) Debugging Chapter 4 Loops: Inspect the code and make sure the following are true. 33 Variables are initialized before entering the loop. Terminating condition stops when the variables have reached the limit. Statements in the body are correct. Update statements are positioned correctly and modify the variables so that they pass the limits in the terminating condition.

Lambert / Osborne Fundamentals of Java 4E Errors in Loops (continued) Debugging Chapter 4 Loops (cont): Use <, <=, >, >= rather than == or !=. If you cannot find an error by inspection, use System.out.println to dump key variables into the terminal window. 34 Immediately after the initialization statements. Inside the loop at the top. Inside the loop at the bottom.

Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops I/O Chapter 4 Dialogs: A small window that contains: A message. A text field for entering input or accepting a default. Command buttons, such as OK or Cancel. The class JOptionPane in the package javax.swing includes varieties of showInputDialog for input dialog boxes.

35 Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops (continued) If the user clicks OK, the dialog box closes and returns the string in the text input field. If the user clicks Cancel, the dialog box closes and returns the value null. If the value is a number, it must be converted to int or double. Chapter 4 An input dialog 36 Lambert / Osborne

Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops (continued) To output a message, use a message dialog box. Chapter 4 Setting Up Lots of Panels: Example: a program that sets up a quilt pattern. 37 JOptionPane.showMessageDialog(anObserver, aString)

User chooses dimensions of the grid (number of rows and columns) and the initial size of the application window. The program displays them in panels. Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Setting Chapter 4 the Preferred Size of a Panel: The preferred size of a panel can be done in different ways. 38

The main window class sets its dimensions at program startup. Give each panel a preferred size and ask the program to shrink-wrap its dimensions to accommodate all of the panels. Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Setting Chapter 4 the Preferred Size of a Panel (cont): Use the setSize method to ask the window to wrap itself around the minimal area necessary to display all of the its components at their preferred size. 39

If a panel does not set its own preferred size, the default is 0 by 0. Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Drawing Multiple Shapes: Example: a bulls-eye. Chapter 4

40 Draw the oval with current color, corner point, and size. Adjust the corner point by subtracting the thickness from each coordinate. Adjust the size by subtracting twice the thickness from each dimension. Adjust the color (white to red or vice versa). Lambert / Osborne Fundamentals of Java 4E Design, Testing, and Debugging Hints Chapter 4

41 Most errors involving selection statements and loops are caught at compile time. Proper use of braces { } affect the logic of a selection statement or loop. When testing if or if-else statements, use test data to exercise the logical branches. Use an if-else statement rather than two if statements if the alternative courses of action are mutually exclusive. When testing a loop, use limit values and typical values. Lambert / Osborne Fundamentals of Java 4E Design, Testing, and Debugging Hints (continued)

Chapter 4 42 Check entry and exit conditions for each loop. For a loop with errors, use debugging output statements to verify the values of the control variable on each iteration. Check the value before the loop is initially entered, after each update, and after the loop is exited. Text files are convenient when the data set is large or is used with different programs, and when the data must be permanently saved. Lambert / Osborne Fundamentals of Java 4E Summary

Chapter 4 43 In this chapter, you learned: Java has some useful operators for extended assignment, such as +=, and for increment and decrement. The Math class provides several useful methods, such as sqrt and abs. The Random class allows you to generate random integers and floating-point numbers. Lambert / Osborne Fundamentals of Java 4E Summary (continued) and if-else statements are used to make one-way and two-way decisions. The comparison operators, such as ==, <=, and >=, return Boolean values that serve as conditions of control statements. The while loop allows the program to run a set of statements repeatedly until a condition

becomes false. if Chapter 4 44 Lambert / Osborne Fundamentals of Java 4E Summary (continued) The Chapter 4 45 for loop is a more concise version of the while loop. Other control statements, such as an if statement, can be nested within loops. A break statement can be used in conjunction with an if statement to terminate a loop early. There are many kinds of logic errors that can occur in loops. Examples are the off-by-one

error and the infinite loop. Lambert / Osborne Fundamentals of Java 4E

Recently Viewed Presentations

  • Aggregation Connector: A Tool for Building Large Molecular ...

    Aggregation Connector: A Tool for Building Large Molecular ...

    Aggregation Connector: A Tool for Building Large Molecular Network Models from Components Thomas C. Jones1, Clifford A. Shaffer1, Alida Palmisano2, Stefan Hoops3, and John J. Tyson2 1Department of Computer Science, Virginia Tech, Blacksburg, VA 2Department of Biological Sciences, Virginia Tech,...
  • Instructions - Electric Reliability Council of Texas

    Instructions - Electric Reliability Council of Texas

    Proxy/Alternate . Segment Representative. Notification? On Proxy/Representative being from Segment.. COPS Meeting 5/8/2018. IDR Meter Read Discussion. Discussion was moved to RMS . ERCOT Updates. Service Availability - March 2018.
  • Creative Court Collections

    Creative Court Collections

    Creative Collections for courts. Hon. Jeff Smith (Indian River County, Clerk & Comptroller) What to consider when creating an in-house collection program. Getting Judicial Cooperation. Working with local agencies. Office hurdles
  • RON: Resilient Overlay Networks

    RON: Resilient Overlay Networks

    RON: Resilient Overlay Networks David Andersen, Hari Balakrishnan, ... network of networks ISPs peer to forward packets ISP exchange route info using BGP The Internet is ill suited to mission-critical applications Commercial peer architecture Performance bottlenecks at peering points Ignores...
  • New Directions and Issues in Second Language Socialization ...

    New Directions and Issues in Second Language Socialization ...

    Study #2: Language Socialization in Multilingual, Multicultural Secondary School Classrooms in Canada (Duff, Mohan & Early, 1997; Duff, 2001, 2002a, 2002b, n.d.) Study #2 examined integration of Asian immigrant students in Western Canadian schools 50% of the school/district students are...
  • www.mrmcfadyen.com

    www.mrmcfadyen.com

    Was making Russian children glad. And children lived in Leningrad. But children lived in Levittown. And hid in the shelters underground. Until the Soviets turned their ships around. And tore the Cuban missiles down. And in that bright October sun....
  • Data Modeling using XML Schemas - WPI

    Data Modeling using XML Schemas - WPI

    The Entity-Relationship Model Part I. CS3431 * CS3431 * Database Design Stages Application Requirements Conceptual Design Logical Design Physical Design Conceptual Schema Logical Schema Physical Schema CS3431 * Conceptual Design What is Conceptual Design?
  • Marijuana and Epilepsy - Wild Apricot

    Marijuana and Epilepsy - Wild Apricot

    Marijuana for Epilepsy in Adults Dr Richard McLachlan- London ... Blue Mountain and CannScience CFPC CoI Templates: Slide 1 Disclosure of Commercial Support This program has received financial support from no one in the form of nothing. This program has...