Announcements. Chapter 3

Similar documents
First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Sources: On the Web: Slides will be available on:

Chapter 2: Elements of Java

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

J a v a Quiz (Unit 3, Test 0 Practice)

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Introduction to Python

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Statements and Control Flow

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Lecture 5: Java Fundamentals III

Java Basics: Data Types, Variables, and Loops

6. Control Structures

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Writing Control Structures

AP Computer Science Java Subset

Computer Programming I

Introduction to Java

Lecture 2 Notes: Flow of Control

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Some Scanner Class Methods

Moving from CS 61A Scheme to CS 61B Java

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Object Oriented Software Design

In this Chapter you ll learn:

Computer Programming I & II*

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

JavaScript: Control Statements I

Install Java Development Kit (JDK) 1.8

Chapter One Introduction to Programming

Object Oriented Software Design

Conditional Statements Summer 2010 Margaret Reid-Miller

13 Classes & Objects with Constructors/Destructors

Selection Statements

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Java Interview Questions and Answers

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Basic Programming and PC Skills: Basic Programming and PC Skills:

Fundamentals of Java Programming

While Loop. 6. Iteration

Two-way selection. Branching and Looping

Lecture 1 Introduction to Java

CS 111 Classes I 1. Software Organization View to this point:

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

VB.NET Programming Fundamentals

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Chapter 1 Java Program Design and Development

Visual Logic Instructions and Assignments

Informatica e Sistemi in Tempo Reale

Computer Science 217

Programming and Data Structures with Java and JUnit. Rick Mercer

#820 Computer Programming 1A

Computer Programming I

Chapter 2 Introduction to Java programming

CS 106 Introduction to Computer Science I

Java (12 Weeks) Introduction to Java Programming Language

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Variables, Constants, and Data Types

Explain the relationship between a class and an object. Which is general and which is specific?

Java Application Developer Certificate Program Competencies

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Exercise 1: Python Language Basics

Windows PowerShell Essentials

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Programming and Software Development CTAG Alignments

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Chapter 3. Input and output. 3.1 The System class

Computing Concepts with Java Essentials

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

AP Computer Science Java Mr. Clausen Program 9A, 9B

Iteration CHAPTER 6. Topic Summary

Pemrograman Dasar. Basic Elements Of Java

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Glossary of Object Oriented Terms

Understanding class definitions

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

LOOPS CHAPTER CHAPTER GOALS

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Syllabus for CS 134 Java Programming

Transcription:

Announcements Project 2 has been posted Due Feb 1st at 10:00pm Work ALONE! Help hours Monday Thursday, 7 10pm LWSN B146 Quiz solutions will be on newsgroup Sign up for newsgroup! We expect you to be reading book. These slides should be a review 1

Flow of Control 2

Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean (optional) Graphics Supplement 3

Compound Statements To include multiple statements in a branch, enclose the statements in braces. if (count < 3) { total = 0; count = 0; } 4

Using ==, cont. is not appropriate for determining if two objects have the same value. if (s1 == s2), where s1 and s2 refer to strings, determines only if s1 and s2 refer the a common memory location. If s1 and s2 refer to strings with identical sequences of characters, but stored in different memory locations, (s1 == s2) is false. == 5

Multibranch if else Statements, cont. class Grader 6

The switch Statement The switch statement is a mutltiway branch that makes a decision based on an integral (integer or character) expression. The switch statement begins with the keyword switch followed by an integral expression in parentheses called the controlling expression. 7

The switch Statement, cont. A list of cases follows, enclosed in braces. Each case consists of the keyword case followed by a constant called the case label a colon a list of statements. The list of cases is searched in order for a case label matching the controlling expression. 8

The switch Statement, cont. The action associated with a matching case label is executed. If no match is found, the case labeled default is executed. The default case is optional, but recommended, even if it simply prints a message. Repeated case labels are not allowed. 9

The switch Statement, cont. class MultipleBirths 10

The switch Statement, cont. The action for each case typically ends with the word break. The optional break statement prevents the consideration of other cases. The controlling expression can be anything that evaluates to an integral type. 11

The for Statement A for statement executes the body of a loop a fixed number of times. example for (count = 1; count < 5; count++) System.out.println(count); System.out.println( Done ); 12

Choosing a Loop Statement If you know how many times the loop will be iterated, use a for loop. If you don t know how many times the loop will be iterated, but it could be zero, use a while loop it will be at least once, use a do while loop. Generally, a while loop is a safe choice. 13

The break Statement in Loops A break statement can be used to end a loop immediately. The break statement ends only the innermost loop or switch statement that contains the break statement. break statements make loops more difficult to understand. Use break statements sparingly (if ever). 14

The break Statement in Loops, cont. class BreakDemo 15

The exit Method Sometimes a situation arises that makes continuing the program pointless. A program can be terminated normally by System.exit(0). example if (numberofwinners == 0) { System.out.println( cannot divide by 0 ); System.exit(0); } 16

Programming with Loops: Outline The Loop Body Initializing Statements Ending a Loop Loop Bugs Tracing Variables 17

The Loop Body To design the loop body, write out the actions the code must accomplish. Then look for a repeated pattern. The pattern need not start with the first action. The repeated pattern will form the body of the loop. Some actions may need to be done after the pattern stops repeating. 18

Initializing Statements Some variables need to have a value before the loop begins. Sometimes this is determined by what is supposed to happen after one loop iteration. Often variables have an initial value of zero or one, but not always. Other variables get values only while the loop is iterating. 19

Ending a Loop If the number of iterations is known before the loop starts, the loop is called a count controlled loop. use a for loop. Asking the user before each iteration if it is time to end the loop is called the ask before iterating technique. appropriate for a small number of iterations Use a while loop or a do while loop. 20

Ending a Loop, cont. For large input lists, a sentinel value can be used to signal the end of the list. The sentinel value must be different from all the other possible inputs. A negative number following a long list of nonnegative exam scores could be suitable. 90 0 10 1 21

Ending a Loop, cont. example reading a list of scores followed by a sentinel value int next = keyboard.nextint(); while (next >= 0) { Process_The_Score next = keyboard.nextint(); } 22

Ending a Loop, cont. class ExamAverager 23

Nested Loops The body of a loop can contain any kind of statements, including another loop. In the previous example the average score was computed using a while loop. This while loop was placed inside a do while loop so the process could be repeated for other sets of exam scores. 24

Declaring Variables Outside Loop Bodies The declaration of variables inside a loop body is repeated with each execution of the loop body. This can be inefficient, depending on the compiler. It the declaration of variables can be moved outside the loop body, generally it is appropriate to do so. 25

Loop Bugs common loop bugs unintended infinite loops off by one errors testing equality of floating point numbers subtle infinite loops The loop may terminate for some input values, but not for others. For example, you can t get out of debt when the monthly penalty exceeds the monthly payment. 26

Subtle Infinite Loops Verify that the monthly payment exceeds the penalty, for example, before entering a loop to determine the number of payments needed to get out of debt. if (payment <= penalty) System.out.println( payment is too small ); else {... 27

Off by One Errors The loop body is repeated one too many times or one too few times. examples < is used when <= should be used or <= is used when < should be used using the index of the last character of a string instead of the length of the string (or vice versa) easy to overlook 28

Testing Equality of Floating point Numbers works satisfactorily for integers and characters. == is not reliable for floating point numbers (which are approximate quantities). Use <= or >= rather than == or!=. == 29

Tracing Variables Tracing variables means watching the variables change while the program is running. Simply insert temporary output statements in your program to print of the values of variables of interest or, learn to use the debugging facility that may be provided by your system. 30

Tracing Variables, cont. 31

The Type boolean Boolean Expressions and Variables Truth Tables and Precedence Rules Input and Output of Boolean Values 32

The Type boolean, cont. The type boolean is a primitive type with only two values: true and false. Boolean variables can make programs more readable. if (systemsareok) instead of if((temperature <= 100) && (thrust >= 12000) && (cabinpressure > 30) && ) 33

Boolean Expressions and Variables Variables, constants, and expressions of type boolean all evaluate to either true or false. A boolean variable can be given the value of a boolean expression by using an assignment operator. boolean ispositive = (number > 0);... if (ispositive)... 34

Naming Boolean Variables Choose names such as ispositive or systemsareok. Avoid names such as numbersign or systemstatus. 35

Truth Tables 36

Precedence Rules Parentheses should be used to indicate the order of operations. When parentheses are omitted, the order of operation is determined by precedence rules. 37

Precedence Rules, cont. Operations with higher precedence are performed before operations with lower precedence. Operations with equal precedence are done left to right (except for unary operations which are done right to left). 38

Precedence Rules, cont. 39

Precedence Rules, cont. In what order are the operations performed? score < min/2 10 score > 90 score < (min/2) 10 score > 90 score < ((min/2) 10) score > 90 (score < ((min/2) 10)) score > 90 (score < ((min/2) 10)) (score > 90) 40

Short circuit Evaluation Sometimes only part of a boolean expression needs to be evaluated to determine the value of the entire expression. If the first operand associated with an is true, the expression is true. If the first operand associated with an && is false, the expression is false. This is called short circuit or lazy evaluation. 41

Short circuit Evaluation, cont. Short circuit evaluation is not only efficient, sometimes it is essential! A run time error can result, for example, from an attempt to divide by zero. if ((number!= 0) && (sum/number > 5)) Complete evaluation can be achieved by substituting & for && or for. 42

Input and Output of Boolean Values example boolean boo = false; System.out.println(boo); System.out.print( Enter a boolean value: ); Scanner keyboard = new Scanner (System.in); boo = keyboard.nextboolean(); System.out.println(boo); 43

Input and Output of Boolean Values, cont. dialog false Enter a boolean value: true true 44

Using a Boolean Variable to End a Loop example boolean numberslefttoread = true while (numberslefttoread) { next = keyboard.nextint() if (next < 0) numberslefttoread = false; else Process_Next_Number } 45

Using a Boolean Variable to End a Loop, cont class BooleanDemo 46

(optional) Graphics Supplement: Outline Specifying a Drawing Color The drawstring Method A JOptionPane Yes/No Window 47

Specifying a Drawing Color When drawing a shape inside an applet s paint method, think of the drawing being done with a pen that can change colors. The method setcolor changes the color of the pen. canvas.setcolor(color.yellow); Drawings done later appear on top of drawings done earlier. 48

Specifying a Drawing Color, cont. 49

Specifying a Drawing Color, cont. 50

Programming Example class MultipleFaces 51

Programming Example, cont. class MultipleFaces, contd. 52

Programming Example, cont. 53

The drawstring Method similar to other drawing methods, but used to draw text canvas.drawstring( Hello,10,20); syntax Graphics_Object.drawString(String, X, Y); 54

A JOptionPane Yes/No Window used to present the user with a yes/no question The window contains the question text two buttons labeled Yes and No. 55

A JOptionPane Yes/No Window, cont. example int answer = JOptionPane.showConfirmDialog(null, End program?, Want to end?, JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) System.exit(0); else System.out.println( once more ); 56

A JOptionPane Yes/No Window, cont. 57

A JOptionPane Yes/No Window, cont. returns an int value named either YES_OPTION or NO_OPTION, but you do not need to think of them as ints. The second argument ( End program? in our example) appears in the window. The third argument ( Want to end? in our example) is displayed as the title of the window. JOptionPane.showConfirmDialog 58

A JOptionPane Yes/No Window, cont. The last argument (JOptionPane.YES_NO_OPTION in our example). requests a window with yes and no buttons. The first argument (null in our example) affects the placement of the window on the screen. Simply use null for now. 59

Summary You have learned about Java branching statements. You have learned about loops. You have learned about the type boolean. (optional) You have learned to use color and the JOptionPane yes/no window. 60