(Java Looping and Conditional Statements). Flow of control Sequential Executes instructions in order Method Calls Transfer control to the methods, then.

Slides:



Advertisements
Similar presentations
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
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.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
ICT Introduction to Programming Chapter 4 – Control Structures I.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
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.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Windows Programming Lecture 03. Pointers and Arrays.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
CS0007: Introduction to Computer Programming
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Information and Computer Sciences University of Hawaii, Manoa
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
BASIC ELEMENTS OF A COMPUTER PROGRAM
Boolean expressions and if-else statements
OBJECT ORIENTED PROGRAMMING I LECTURE 8 GEORGE KOUTSOGIANNAKIS
Selections Java.
Lecture 5: Some more Java!
Java for Android is specific
Chapter 6 More Conditionals and Loops
Selenium WebDriver Web Test Tool Training
User input We’ve seen how to use the standard output buffer
Java Programming: From Problem Analysis to Program Design, 4e
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Control Structures – Selection
Advanced Programming Behnam Hatami Fall 2017.
Chapter 4 Control Statements: Part I
Chapter 10 Programming Fundamentals with JavaScript
Starting JavaProgramming
7 Arrays.
Java - Data Types, Variables, and Arrays
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Expressions and Assignment
The System.exit() Method
Control Structure Chapter 3.
7 Arrays.
Arrays in Java.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Suggested self-checks: Section 7.11 #1-11
Unit 3: Variables in Java
Just Enough Java 17-May-19.
Conditionals and Loops
Introduction to C Programming
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Control Structure.
How do you do the following?
Arrays.
Presentation transcript:

(Java Looping and Conditional Statements)

Flow of control Sequential Executes instructions in order Method Calls Transfer control to the methods, then returns with or without value Selection Executes different instructions depending on data Looping Repeat a set of instructions for different data

 Used to determine if values of two expressions are equal or not equal  Result is true or false == Type is Binary, meaning “is equal to” != Type is Binary, meaning “is not equal to” Example (age == 39) means is age equal to 39, returns true or false (age != 39) means is age not equal to 39, returns true or false  Only use equality on primitive types, and not objects, results may be different  Don’t confuse (equality operator) == with (assignment operator) =, they are different

 < binary “is less than”  > binary “is greater than”  <= binary “is less than or equal to”  >= binary “is greater than or equal to”

 ! unary NOT  && Binary AND  || Binary OR  Operands must be Boolean expressions

 Short circuit evaluation Compiler starts evaluating from the left and moving to the right. As soon as it can determine what the outcome is going to be, then it will terminate. Example if(10 < 11 && 11 == 11) The compiler will stop evaluating after the 10 < 11

 De Morgan’s Law !(A && B) == !A || !B !(A || B) == !A && !B  Unary operators take precedence !A || !B == (!A) || (!B)

 If Statement Used when program should perform an operation for one set of data, but do nothing for all other data. Syntax: if (condition) { //true block //executed if condition is true }  Curly braces are optional if true block contains only one statement.

Example: import java.util.Scanner; public class Grade { public static void main( String [] args ) { Scanner scan = new Scanner( System.in ); System.out.print( "Enter a grade > " ); int grade = scan.nextInt( ); if ( grade >= 50 ) System.out.println( "pass" ); System.out.println( "Fail" ); } } Don’t put semi-colons after the condition

 If Else Statement Used when program should perform an operation when a condition is true for one set of data, and then do something else when the condition is false another set of data  Again, no need for curly braces if only one statement within condition

Example: import java.util.Scanner; public class Divid { public static void main( String [] args ) { Scanner scan = new Scanner( System.in ); System.out.print( "Enter the dividend > " ); int dividend = scan.nextInt( ); System.out.print( "Enter divisor > " ); int divisor = scan.nextInt( ); if ( divisor == 0 ) System.out.println( "divide by zero" ); else System.out.println( dividend + " / " + divisor + " = " + ( dividend / divisor ) ); } }

 If Else If Statement  Used when program should perform an operation when a condition is true for one set of data, and then evaluate another operation when the first condition is false.  Nested if statements  Used when program should evaluate another condition when a condition evaluates to true

Examples of terminating nested if statements  Dangling Else Generates compiler error  Testing techniques A good test suite executes every statement in your program (could be exhaustive).  Comparing doubles/floats decimals Give yourself a threshold if(Math.abs(dbl1 – dbl2) <.0001) …

 Comparing characters Comparisons of characters are comparing the Unicode number of the character  Comparing objects Comparisons of objects that do not override the Object.equals method are comparing the instance of object in memory, not the data of the object compare objects use the equals method.

 Comparing strings Strings are objects, so use the equals method You can also use equalsIgnoreCase are defined in the string class and compareTo – used for sorting  Conditional operator A shortcut to simplify a simple if else statement Example String result = (testString == “help” ? “needs help” : “does not need help”);

 Switch Statement Only accepts character or integer (byte, short, or int) expression to constants of the same type. Can group case statements case 1: case 2: // do something break;

Arrays are to data as loops are to control flow.

Arrays Arrays are the basic way to store large numbers of values. Every programming language you're likely to use has arrays as part of the fundamental language, altho with many little variations on how they work.

An array can store many similar values in memory. Each value is accessed by specifying an integer subscript or index in brackets following the array name. "Array" in Java means approximately the same thing as array, matrix, or vector does in math. Unlike math and some other programming languages, in Java you must both declare an array and allocate a fixed amount of memory for it.

Declaring an Array An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable.

The declaration allocates only enough space for a reference to an array (typically 4 bytes), but doesn't create the actual array object.  String[] args; // args is an array of Strings  int[] scores; // scores is an array of ints  JButton[] controlButtons; // controlButtons is an array of JButtons No size in declaration. Unlike some languages, never put the size of the array in the declaration because an array declaration specifies only the element type and the variable name. The size is specified when you allocate space for the array.

Names - Plurals or collective nouns are most common for array names Most programming guidelines suggest using plural names, or nouns denoting a collection of things, for arrays and other collections of multiple values. This is not a rigid rule, and your choice will often be based on linguistic sensitives.

Allocate an array object with new Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99]. int[] a; // Declare a to be an array of ints a = new int[100]; // Allocate an array of 100 ints These are often combined in one line. int[] a = new int[100]; // Declare and allocate.

Subscripts (indexes/indices) Subscripts are enclosed in square brackets []. x i in mathematics is x[i] in Java, and is pronounced "x-sub-i". Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays).

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behaver of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Zero-based indexing is a constant annoyance of Java's zero-based indexing. The natural human value for hours or days should be used as an index to make the program most readable, but this would mean starting with 1, not zero

Initial array element values -- zero/null/false When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float,...), false for boolean, and null for all object types

Array Initialization When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example: String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Array diagrams This code declares and initializes an array. int[] a = {1, 2, 4, 8, 16}; Arrays are often represented with diagrams that represent their memory use.

Each box represents the amount of memory needed to hold one array element. For ints this is 4 bytes. The array variable, a, is a reference (ie, memory address in the heap) of the block of memory that holds the actual array elements.

References are often represented by a black disk with an arrow pointing to the data they reference. Most often array diagrams are written vertically, but sometimes the cells are arranged horizontally, especially for arrays of characters. Of course in the actual physical memory there is no such idea as vertical or horizontal.

Array variables are references to a block of elements When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied

For example: int[] a = new int[] {100, 99, 98}; // "a" references the array object. int[] b; // "b" doesn't reference anything. b = a; // Now "b" refers to the SAME array as "a" b[1] = 0; // Also changes a[1] because a and b refer to the same array

Common array problems Some common array programming mistakes are: Runtime error: Forgetting that array subscripts start with zero. Compile-time error: Writing a.length() instead of a.length. The length() method is used with Strings, not arrays. Compile-time error: Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

THANK YOU!